The problem of jdk8stream map fetching an item in the object

Keywords: Java

jdk8 Stream map takes the value of an item in the object

The problem of map taking the value of an item in an object

    ...
   
    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());
            }
        });
    
    ...

Analysis: when the value is obtained, it will be processed. A null pointer will appear. The Bug is that a null object will appear after a value is taken

 


 

If size equals 2, the original data will be returned to the corresponding location by taking a value. If the first object does not meet the requirements, it will be null. If the second object meets the requirements, the data will be displayed.

 


 

After the above analysis, the problem has been found. null filtering and code adjustment are needed

    ...
        
       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());
            }
        });
    ...

Inertia: generally, the map of jdk8 stream is used to take a value according to a certain item. After the value is taken, it is almost finished. If you continue to recycle this collection, you will find bug s. You can filter it manually. This is also a pit here

    ...
         screenWiperResponseList.stream().map(CarAdapterForScreenWiperResponse::getPartData).filter(x -> x != null).collect(Collectors.toList());
    ...
    

Posted by jeff_papciak on Sat, 30 Nov 2019 22:43:39 -0800