java-ee - java8的Collectors.reducing()
问题描述
Map<Integer, OperationCountVO> collect = operationInfos.stream().collect(Collectors.groupingBy(OperationCountVO::getCityId, Collectors.reducing(new OperationCountVO(), (OperationCountVO v1, OperationCountVO v2) -> {v1.setSurgeryCount(v1.getSurgeryCount() + v2.getSurgeryCount());v1.setCityId(v2.getCityId());return v1; })));
大概就是我想对operationInfos集合按照里面的cityId进行分组,然后cityId一样的话,把对象的SurgeryCount加起来返回,但是现在 第一次的v1是null,执行v1.setSurgeryCount(v1.getSurgeryCount() + v2.getSurgeryCount());的时候报了空指针,我哪里写的有问题吗?
问题解答
回答1:若v1是null的话,那就说明operationInfos集合里面是有null的,因为是要根据OperationCountVO的cityId进行分组,那OperationCountVO一定不为null,建议前面直接加filter过滤掉
Map<Integer, OperationCountVO> collect = operationInfos.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(OperationCountVO::getCityId, Collectors.reducing(new OperationCountVO(), (OperationCountVO v1, OperationCountVO v2) -> {v1.setSurgeryCount(v1.getSurgeryCount() + v2.getSurgeryCount());v1.setCityId(v2.getCityId());return v1; })));
刚评论发现...可能报错原因还有可能是,Collectors.reducing中的第一个参数为new OperationCountVO(),若new出来的OperationCountVO对象的surgeryCount为Integer类型,不是基本类型的话,所以没有初始化,surgeryCount就为null,在做v1.getSurgeryCount() + v2.getSurgeryCount()操作的时候就可能报错了呀
(ps:对于reducing中的第二个参数BinaryOperator,最好还是封装到OperationCountVO对象中,看起来代码更声明式一点...这样写代码太丑了...哈哈...或者写出来,写成一个静态final变量更好,到时候可以到处调用嘛)
比如直接在本类上新增一个SurgeryCount属性合并的BinaryOperator,名字就叫surgeryCountMerge
public static final BinaryOperator<OperationCountVO> surgeryCountMerge = (v1, v2) -> { v1.setSurgeryCount(v1.getSurgeryCount() + v2.getSurgeryCount()); return v1;}
这样下面代码就可以改成
Map<Integer, OperationCountVO> collect = operationInfos.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(OperationCountVO::getCityId,Collectors.reducing(new OperationCountVO(), surgeryCountMerge));
这样写了之后,其实发现题主可能做麻烦了点,最后不就是为了返回一个Map嘛,所以建议不使用groupingBy,毕竟分组返回结果是一对多这样的结构,不是一对一的结构,那直接使用toMap嘛,直接点
Map<Integer, OperationCountVO> collect = operationInfos.stream().filter(Objects::nonNull).collect(Collectors.toMap(OperationCountVO::getCityId, Function.identity(), surgeryCountMerge));
这样快多了噻,还不会报错,哈哈
相关文章:
1. 如何判断数据库的库和表是否存在?2. python - nginx为什么不能反代图片?3. css - div内部滚动,安卓没有滚动条(非body滚动),有什么办法可以显示吗?4. python - 如何使用jsom.dumps获得完整的json数据?5. python - django里GROUP BY 如何写这样的mysql语句?6. 数据库安全 - 在公网上部署mysql数据库,安全方面需要做到哪些注意事项7. php mysql_query()问题8. python2.7 - 在Eclipse开发Python,怎么去掉控制台输出的其他消息??9. java - sonar测试遇到的问题?10. css - 定位为absolute的父元素中的子元素 如何设置在父元素的下面?
