jdk8 Stream map 取對象中某項的值 map 取對象中某項的值 問題 ... List<ScreenWiperResponse> screenWiperList= screenWiperResponseList.stream().map(CarAdapterForScreenWiperR ...
jdk8 Stream map 取對象中某項的值
map 取對象中某項的值 問題
...
List<ScreenWiperResponse> screenWiperList= screenWiperResponseList.stream().map(CarAdapterForScreenWiperResponse::getPartData).collect(Collectors.toList());
List<String> productModelList = new LinkedList<>();
log.info("screenWiperList: {}", screenWiperList);
screenWiperList.forEach(screenWiperResponse -> {
if (CollectionUtil.isNotNullOrEmpty(screenWiperResponse.getPartNos())){
productModelList.addAll(screenWiperResponse.getPartNos());
}
});
...
分析:拿到值就做處理,出現空指針,出現的Bug是,根據某項值進行取值後,會出現null對象
size等於2是,原數據,通過取某項值後,返回對應位置的數據,第一個對象不符合,為null,第二個對象符合取值條件,就顯示有數據。
經過上面分析,問題已經找到,需要把null過濾,代碼調整
...
List<ScreenWiperResponse> screenWiperList= screenWiperResponseList.stream().map(CarAdapterForScreenWiperResponse::getPartData).filter(x -> x != null).collect(Collectors.toList());
List<String> productModelList = new LinkedList<>();
log.info("screenWiperList: {}", screenWiperList);
screenWiperList.forEach(screenWiperResponse -> {
if (CollectionUtil.isNotNullOrEmpty(screenWiperResponse.getPartNos())){
productModelList.addAll(screenWiperResponse.getPartNos());
}
});
...
慣性:一般用jdk8 stream的map根據某一項取值,取完之後,基本就結束了,如果你繼續把這個集合進行迴圈處理,就會發現bug ,手動過濾下,此處也算是一坑
...
screenWiperResponseList.stream().map(CarAdapterForScreenWiperResponse::getPartData).filter(x -> x != null).collect(Collectors.toList());
...