Java stream - Sort a List to a HashMap of Lists

非 Y 不嫁゛ 提交于 2019-12-03 06:20:46

问题


Let's say I have a Dog class.

Inside it I have a Map<String,String> and one of the values is Breed.

public class Dog {
    String id;
    ...
    public Map<String,String>
}

I want to get a Map of Lists:

HashMap<String, List<Dog>> // breed to a List<Dog>

I'd prefer to use a Stream rather than iterating it.

How can I do it?


回答1:


You can do it with groupingBy.

Assuming that your input is a List<Dog>, the Map member inside the Dog class is called map, and the Breed is stored for the "Breed" key :

List<Dog> dogs = ...
HashMap<String, List<Dog>> map = dogs.stream()
                                     .collect (Collectors.groupingBy(d -> d.map.get("Breed")));



回答2:


The great answer above can further be improved by using functional programming notation:

List<Dog> dogs = ...
HashMap<String, List<Dog>> map = dogs.stream()
     .collect(Collectors.groupingBy(Dog::getBreed)); 


来源:https://stackoverflow.com/questions/28064263/java-stream-sort-a-list-to-a-hashmap-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!