Java stream - Sort a List to a HashMap of Lists
JavaJava 8HashmapJava StreamJava Problem Overview
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?
Java Solutions
Solution 1 - Java
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 = ...
Map<String, List<Dog>> map = dogs.stream()
.collect(Collectors.groupingBy(d -> d.map.get("Breed")));
Solution 2 - Java
The great answer above can further be improved by method reference notation:
List<Dog> dogs = ...
Map<String, List<Dog>> map = dogs.stream()
.collect(Collectors.groupingBy(Dog::getBreed));
Solution 3 - Java
List<Map<String,Object>> inAppropWords = new ArrayList<>();
Map<String, Object> s = new HashMap<String, Object>();
s.put("type", 1);
s.put("name", "saas");
Map<String, Object> s1 = new HashMap<String, Object>();
s1.put("type", 2);
s1.put("name", "swwaas");
Map<String, Object> s2 = new HashMap<String, Object>();
s2.put("type", 1);
s2.put("name", "saqas");
inAppropWords.add(s);
inAppropWords.add(s1);
inAppropWords.add(s2);
Map<Integer, List<String>> t = inAppropWords.stream().collect(Collectors.groupingBy(d -> AppUtil.getInteger(d.get("type")),Collectors.mapping(d -> String.valueOf(d.get("name")),Collectors.toList())));
System.out.println(t);