国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

java-ee - java8的Collectors.reducing()
三叔
三叔 2017-07-03 11:43:35
0
1
1429
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的,因為是要根據(jù)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;
            })));

剛評論發(fā)現(xiàn)...可能報錯原因還有可能是,Collectors.reducing中的第一個參數(shù)為new OperationCountVO(),若new出來的OperationCountVO對象的surgeryCountInteger類型,不是基本類型的話,所以沒有初始化,surgeryCount就為null,在做v1.getSurgeryCount() + v2.getSurgeryCount()操作的時候就可能報錯了呀

(ps:對于reducing中的第二個參數(shù)BinaryOperator,最好還是封裝到OperationCountVO對象中,看起來代碼更聲明式一點...這樣寫代碼太丑了...哈哈...或者寫出來,寫成一個靜態(tài)final變量更好,到時候可以到處調(diào)用嘛)

比如直接在本類上新增一個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));

這樣寫了之后,其實發(fā)現(xiàn)題主可能做麻煩了點,最后不就是為了返回一個Map嘛,所以建議不使用groupingBy,畢竟分組返回結(jié)果是一對多這樣的結(jié)構(gòu),不是一對一的結(jié)構(gòu),那直接使用toMap嘛,直接點

Map<Integer, OperationCountVO> collect = operationInfos.stream()
        .filter(Objects::nonNull)
        .collect(Collectors.toMap(OperationCountVO::getCityId, Function.identity(), surgeryCountMerge));

這樣快多了噻,還不會報錯,哈哈

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage