当前位置: 移动技术网 > IT编程>开发语言>Java > jdk8stream map取对象中某项的问题

jdk8stream map取对象中某项的问题

2019年01月15日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网