描述: 取list集合中两个字段,且将两个字段作为key ,map,利用steam流转为map集合,且满足key相同时,将value转为List集合
查询到资料 转自https://my.oschina.net/u/3725073/blog/1807970/
List userList = new ArrayList<>();
userList.add(new User(1L, "aaa"));
userList.add(new User(2L, "bbb"));
userList.add(new User(3L, "ccc"));
userList.add(new User(2L, "ddd"));
userList.add(new User(3L, "eee"));
资料给出的解决方案
userList.stream().collect(Collectors.toMap(User::getId,
e->Arrays.asList(e.getUsername()),
(List oldList, List newList) ->{
oldList.addAll(newList);returnoldList;
}));
实际操作后
报空指针错误
解决方式
userList.stream().collect(Collectors.toMap(User::getId,
e ->new ArrayList<>(Arrays.asList(e.getUsername())),
(List oldList, List newList) ->{
oldList.addAll(newList);
returnoldList;
}));
拓展新需求 现在有一个集合List的list,包括n个字段,假设为四个字段 (name,type,size,color),List中apple的name字段有相同部分,
又有一个Apple的dto,包括字段要比Apple中少,假设包括name和color字段,,现在要将List转为Map,且Map的key为name,value为dto的集合(List)
该如何实现?
Map> map =list.stream().collect(Collectors.toMap(Apple::getName,
e-> new ArrayList<>(Arrays.asList(newAppleDTO(e.getName(), e.getColor()))),
(List oldList, List newList) ->{
oldList.addAll(newList);returnoldList;
}));
注意:此时有个dto的构造方法,所以dto类中得有这个构造方法才行,感觉不用讲啊,都学到lambda了,都懂的
public AppleDTO(string name,string color){
this.name = name;
this.color = color;
}