美文网首页
java stream操作,Collectors.groupBy

java stream操作,Collectors.groupBy

作者: 我是大飛 | 来源:发表于2022-07-06 14:35 被阅读0次

问题描述

java 集合list调用stream转map操作,并使用Collectors.groupbying分组时,若没有判空处理,会报空指针异常
如下面的代码:

        // 当User#name 属性有null时,会报空指针异常
        User user1 = new User(18, "zhangsan", new Class("一班"));
        User user2 = new User(19, "lisi", new Class("二班"));
        User user3 = new User(20, "wangwu", new Class("一班"));
        User user4 = new User(null, null, null);
        List<User> users = Arrays.asList(user1, user2, user3, user4);
        Map<String, List<User>> map = users.stream().collect(Collectors.groupingBy(e -> e.getName()));

解决放方案:

采用Optional封装

        User user1 = new User(18, "zhangsan", new Class("一班"));
        User user2 = new User(19, "lisi", new Class("二班"));
        User user3 = new User(20, "wangwu", new Class("一班"));
        User user4 = new User(null, null, null);
        List<User> users = Arrays.asList(user1, user2, user3, user4);
        Map<Optional<String>, List<User>> map = users.stream().collect(Collectors.groupingBy(e -> Optional.ofNullable(e.getName())));

转换后的map如下:

Optional.empty:[User{age=16, name='null', aClass=null}]
Optional[lisi]:[User{age=19, name='lisi', aClass=Class{name='二班'}}]
Optional[zhangsan]:[User{age=18, name='zhangsan', aClass=Class{name='一班'}}]
Optional[wangwu]:[User{age=20, name='wangwu', aClass=Class{name='一班'}}]

相关文章

网友评论

      本文标题:java stream操作,Collectors.groupBy

      本文链接:https://www.haomeiwen.com/subject/asrybrtx.html