zoukankan      html  css  js  c++  java
  • 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;

    }

     

     

  • 相关阅读:
    lintcode197- Permutation Index- easy
    lintcode10- String Permutation II- medium
    lintcode211- String Permutation- easy
    lintcode51- Previous Permutation- medium
    lintcode52- Next Permutation- medium
    lintcode108- Palindrome Partitioning II- medium
    lintcode136- Palindrome Partitioning- medium
    lintcode153- Combination Sum II- medium
    lintcode521- Remove Duplicate Numbers in Array- easy
    lintcode135- Combination Sum- medium
  • 原文地址:https://www.cnblogs.com/qiannianguyao/p/12916458.html
Copyright © 2011-2022 走看看