java stream使用需要避开这些坑

本文介绍了在Java中使用`toMap`方法处理List到Map转换时遇到的重复键问题,以及如何避免Key冲突。同时,讨论了如何在使用`mapToInt`统计列表值时处理可能出现的空指针异常。
摘要由CSDN通过智能技术生成

目录

测试类

使用中的坑

(1)toMap

(2)使用mapToInt等做统计


测试类

student类

@Data
public class Student {

    private String name;

    private Integer age;

    private Integer score;

    public Student(String name,Integer age,Integer score){
           this.name = name;
           this.age =age;
           this.score = score;
    }
}
public class Test {

    public static void main(String[] args) {
        List<Student> stList = new ArrayList<>();
        stList.add(new Student("AA",1,1));
        stList.add(new Student("AA",1,1));
        stList.add(new Student("BB",1,1));
        stList.add(new Student("CC",1,null));
        //TODO
      
    }


}

使用中的坑

(1)toMap

使用stream很常用场景,就是把list转map, 很多时候,写法如下:

stList.stream().collect(Collectors.toMap(Student::getName, Function.identity()));

放到上面测试类执行,发现会报错Exception in thread "main" java.lang.IllegalStateException: Duplicate key Student(name=AA, age=1, score=1)

有key重复会报错,跟我们以为的后面出现会覆盖前面相同的key理解不同,现场环境有垃圾数据或者重复数据,这个错误很容易出现。

防止抛出写法:

stList.stream().collect(Collectors.toMap(Student::getName, Function.identity(),(a1,a2)->a1));

意思是,以第一次出现的值为准,如果有逻辑,可以自行修改取值逻辑

(2)使用mapToInt等做统计

如果求学生的总分数,很多人就这么写

int ss = stList.stream().mapToInt(Student::getScore).sum();

执行之后,发现报错

Exception in thread "main" java.lang.NullPointerException
    at java.util.stream.ReferencePipeline$4$1.accept(ReferencePipeline.java:210)

如果不用stream,用普通的for循环统计总数,估计大家都不会忘记对getScore()进行判空,用stream求统计值,同样也要考虑空指针

int ss = stList.stream().filter(a->a!=null && a.getScore()!=null).mapToInt(Student::getScore).sum();

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值