成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

java-ee - java8的Collectors.reducing()

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

問(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ò),哈哈

標(biāo)簽: java
相關(guān)文章: