java stream 流遇到的问题

问题一:  Exception in thread "main" java.lang.NullPointerException: element cannot be mapped to a null key

原因:当使用stream流进行分组,分组的 key 为 null 则报上述错误 

     @Data
        class Studet{
            private int id;
            private String name;

            public Studet() {
            }

            public Studet(int id) {
                this.id = id;
            }

        }

        Map<Integer, List<Studet>> studentMap = Lists.newArrayList(new Studet(), new Studet(1), new Studet(2))
                .stream().collect(Collectors.groupingBy(Studet::getId));

问题二:Exception in thread "main" java.lang.IllegalStateException: Duplicate key 2

原因:当使用stream流转map时,当前集合中作为key的属性相同时则报上述错误。

 @Data
        class Studet{
            private int id;
            private String name;

            public Studet() {
            }
            public Studet(int id) {
                this.id = id;
            }

            public Studet(int id, String name) {
                this.id = id;
                this.name = name;
            }
        }

        Map<Integer, String> studentMap = Lists.newArrayList( new Studet(1,"1"), new Studet(2,"2"), new Studet(2,"2"))
                .stream().collect(Collectors.toMap(Studet::getId, Studet::getName));

问题三:Exception in thread "main" java.lang.NullPointerException
原因:当使用stream流转map时,作为map的value也不可以为null,否则报上述空指针问题
 

  @Data
    static class Student{
        private int id;
        private String name;
    }

    public static void main(String[] args) {

        Student student1 = new Student();
        student1.setId(0);
        Student student2 = new Student();
        student2.setId(1);
        Student student3 = new Student();
        student3.setId(2);

        List<Student> students = new ArrayList<>();
        students.add(student1);
        students.add(student2);
        students.add(student3);

        Map<Integer, String> studentMap = students.stream().collect(Collectors.toMap(Student::getId, Student::getName));
        
    }

总结:当使用stream流生成map映射对象时,作为key和作为value的属性都不能为空

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小花客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值