java-ee - java8的Collectors.reducing()
問(wèn)題描述
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; })));
大概就是我想對(duì)operationInfos集合按照里面的cityId進(jìn)行分組,然后cityId一樣的話,把對(duì)象的SurgeryCount加起來(lái)返回,但是現(xiàn)在 第一次的v1是null,執(zhí)行v1.setSurgeryCount(v1.getSurgeryCount() + v2.getSurgeryCount());的時(shí)候報(bào)了空指針,我哪里寫的有問(wèn)題嗎?
問(wèn)題解答
回答1:若v1是null的話,那就說(shuō)明operationInfos集合里面是有null的,因?yàn)槭且鶕?jù)OperationCountVO的cityId進(jìn)行分組,那OperationCountVO一定不為null,建議前面直接加filter過(guò)濾掉
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; })));
剛評(píng)論發(fā)現(xiàn)...可能報(bào)錯(cuò)原因還有可能是,Collectors.reducing中的第一個(gè)參數(shù)為new OperationCountVO(),若new出來(lái)的OperationCountVO對(duì)象的surgeryCount為Integer類型,不是基本類型的話,所以沒(méi)有初始化,surgeryCount就為null,在做v1.getSurgeryCount() + v2.getSurgeryCount()操作的時(shí)候就可能報(bào)錯(cuò)了呀
(ps:對(duì)于reducing中的第二個(gè)參數(shù)BinaryOperator,最好還是封裝到OperationCountVO對(duì)象中,看起來(lái)代碼更聲明式一點(diǎn)...這樣寫代碼太丑了...哈哈...或者寫出來(lái),寫成一個(gè)靜態(tài)final變量更好,到時(shí)候可以到處調(diào)用嘛)
比如直接在本類上新增一個(gè)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));
這樣寫了之后,其實(shí)發(fā)現(xiàn)題主可能做麻煩了點(diǎn),最后不就是為了返回一個(gè)Map嘛,所以建議不使用groupingBy,畢竟分組返回結(jié)果是一對(duì)多這樣的結(jié)構(gòu),不是一對(duì)一的結(jié)構(gòu),那直接使用toMap嘛,直接點(diǎn)
Map<Integer, OperationCountVO> collect = operationInfos.stream().filter(Objects::nonNull).collect(Collectors.toMap(OperationCountVO::getCityId, Function.identity(), surgeryCountMerge));
這樣快多了噻,還不會(huì)報(bào)錯(cuò),哈哈
相關(guān)文章:
1. javascript - vscode alt+shift+f 格式化js代碼,通不過(guò)eslint的代碼風(fēng)格檢查怎么辦。。。2. javascript - 這不是對(duì)象字面量函數(shù)嗎?為什么要new初始化?3. javascript - [js]為什么畫布里不出現(xiàn)圖片呢?在線等4. javascript - 如何將一個(gè)div始終固定在某個(gè)位置;無(wú)論屏幕和分辨率怎么變化;div位置始終不變5. javascript - 原生canvas中如何獲取到觸摸事件的canvas內(nèi)坐標(biāo)?6. javascript - 求解答:實(shí)例對(duì)象調(diào)用constructor,此時(shí)constructor內(nèi)的this的指向?7. javascript - 有什么比較好的網(wǎng)頁(yè)版shell前端組件?8. html - vue項(xiàng)目中用到了elementUI問(wèn)題9. html5 - 有可以一次性把所有 css外部樣式轉(zhuǎn)為html標(biāo)簽內(nèi)style=" "的方法嗎?10. python - 如何判斷爬蟲已經(jīng)成功登陸?
