java-ee - java8的Collectors.reducing()
三叔
三叔 2017-07-03 11:43:35
0
1
1249
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;
            })));

Wahrscheinlich möchte ich die operationInfos-Sammlung nach der darin enthaltenen cityId gruppieren und dann, wenn die cityId dieselbe ist, den SurgeryCount des Objekts hinzufügen und zurückgeben, aber jetzt ist die erste v1 null,
Execute v1.setSurgeryCount(v1. getSurgeryCount() + v2.getSurgeryCount()); hat einen Nullzeiger gemeldet. Stimmt etwas mit der Stelle, an der ich ihn geschrieben habe?

三叔
三叔

Antworte allen(1)
伊谢尔伦

v1null的话,那就说明operationInfos集合里面是有null的,因为是要根据OperationCountVOcityId进行分组,那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对象的surgeryCountInteger类型,不是基本类型的话,所以没有初始化,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));

这样快多了噻,还不会报错,哈哈

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!