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;

}

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM