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進行分組,然后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));
這樣快多了噻,還不會報錯,哈哈
相關文章:
1. javascript - vscode alt+shift+f 格式化js代碼,通不過eslint的代碼風格檢查怎么辦。。。2. javascript - 如何將一個div始終固定在某個位置;無論屏幕和分辨率怎么變化;div位置始終不變3. html5 - 有可以一次性把所有 css外部樣式轉為html標簽內style=" "的方法嗎?4. javascript - 有什么比較好的網頁版shell前端組件?5. java - 如何寫一個intellij-idea插件,實現編譯時修改源代碼的目的6. javascript - 原生canvas中如何獲取到觸摸事件的canvas內坐標?7. java 中Long 類型如何轉換成Double?8. javascript - 求解答:實例對象調用constructor,此時constructor內的this的指向?9. html - vue項目中用到了elementUI問題10. javascript - [js]為什么畫布里不出現圖片呢?在線等
