欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jdk8stream map取对象中某项的问题

程序员文章站 2022-04-15 16:56:52
jdk8 Stream map 取对象中某项的值 map 取对象中某项的值 问题 ... List 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对象

 

jdk8stream map取对象中某项的问题
jdk8stream map取对象中某项的问题

 

size等于2是,原数据,通过取某项值后,返回对应位置的数据,第一个对象不符合,为null,第二个对象符合取值条件,就显示有数据。

 

jdk8stream map取对象中某项的问题
jdk8stream map取对象中某项的问题

 

经过上面分析,问题已经找到,需要把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());
    ...