Java 8 lambda Stream list to Map key 重复 value合并到Collection

描述: 取list集合中两个字段,且将两个字段作为key ,map,利用steam流转为map集合,且满足key相同时,将value转为List集合

 

查询到资料 转自https://my.oschina.net/u/3725073/blog/1807970/

List<User> 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<String> oldList, List<String> newList) -> {
                    oldList.addAll(newList);
                    return oldList;
                }));

实际操作后

报空指针错误

解决方式

userList.stream().collect(Collectors.toMap(User::getId,
                e -> new ArrayList<>(Arrays.asList(e.getUsername())),
                (List<String> oldList, List<String> newList) -> {
                    oldList.addAll(newList);
                    return oldList;
                }));

拓展新需求 现在有一个集合List<Apple>的list,包括n个字段,
假设为四个字段 (name,type,size,color),List中apple的name字段有相同部分

又有一个Apple的dto,包括字段要比Apple中少,假设包括name和color字段,,现在要将List<Apple>转为Map,且Map的key为name,value为dto的集合(List<AppleDTO>)

该如何实现?
Map<String, List<AppleDTO>> map = list.stream().collect(Collectors.toMap(Apple::getName,
e -> new ArrayList<>(Arrays.asList(new AppleDTO(e.getName(), e.getColor()))),
(List<AppleDTO> oldList, List<AppleDTO> newList) -> {
                    oldList.addAll(newList);
                    return oldList;
                }));

注意:此时有个dto的构造方法,所以dto类中得有这个构造方法才行,感觉不用讲啊,都学到lambda了,都懂的

public AppleDTO(string name,string color){

  this.name = name;

  this.color = color;

}

 

 

 

 

posted @ 2020-05-19 13:39  前年老妖  阅读(8986)  评论(0编辑  收藏  举报