问题
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 List
s:
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