问题描述
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='一班'}}]
网友评论