国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

java-ee - java8的Collectors.reducing()

瀏覽:159日期:2023-10-18 15:09:42

問題描述

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));

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

標簽: java
相關文章:
主站蜘蛛池模板: 延津县| 广东省| 海盐县| 巩留县| 宁安市| 东光县| 仁寿县| 阳信县| 黄大仙区| 巢湖市| 东兴市| 上虞市| 东乡县| 兴安盟| 邢台县| 云梦县| 阜阳市| 彭州市| 若尔盖县| 寻乌县| 昌江| 祁门县| 广宗县| 静安区| 通许县| 清水县| 台湾省| 承德县| 抚顺县| 桓台县| 会昌县| 大名县| 遂溪县| 县级市| 沈丘县| 衡水市| 景宁| 乐业县| 墨竹工卡县| 六枝特区| 荆州市|