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進(jìn)行分組,然后cityId一樣的話,把對象的SurgeryCount加起來返回,但是現(xiàn)在 第一次的v1是null,執(zhí)行v1.setSurgeryCount(v1.getSurgeryCount() + v2.getSurgeryCount());的時候報了空指針,我哪里寫的有問題嗎?
問題解答
回答1:若v1是null的話,那就說明operationInfos集合里面是有null的,因為是要根據(jù)OperationCountVO的cityId進(jìn)行分組,那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對象的surgeryCount為Integer類型,不是基本類型的話,所以沒有初始化,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));
這樣快多了噻,還不會報錯,哈哈
相關(guān)文章:
1. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?2. javascript - 關(guān)于audio標(biāo)簽暫停的問題3. 網(wǎng)頁爬蟲 - 用Python3的requests庫模擬登陸B(tài)ilibili總是提示驗證碼錯誤怎么辦?4. 請教各位大佬,瀏覽器點 提交實例為什么沒有反應(yīng)5. css - 對于類選擇器使用的問題6. Matlab和Python編程相似嗎,有兩種都學(xué)過的人可以說說嗎7. 大家好,請問在python腳本中怎么用virtualenv激活指定的環(huán)境?8. javascript - 移動端textarea不能上下滑動,該怎么解決?9. javascript - 微信小程序封裝定位問題(封裝異步并可能多次請求)10. javascript - Web微信聊天輸入框解決方案
