Collectors Multilevel grouping
public class CollectorsGroupingFlight {
public static void main(String[] args) {
List<Animal> animals = Arrays.asList(
new Animal("Tiger", "Wild", "Small"),
new Animal("Cow", "Domestic", "Large"),
new Animal("Lion", "Wild", "Large"),
new Animal("Goat", "Domestic", "Small"),
new Animal("Dog", "Domestic", "Small"));
Map<String, Map<String, List<Animal>>> result = animals
.stream()
.collect(groupingBy(Animal::getType,
groupingBy(Animal::getSize)));
System.out.println("Result: "+result);
}
}
Output:
Result: {
Wild={
Small=[Animal [name=Tiger, type=Wild, size=Small]],
Large=[Animal [name=Lion, type=Wild, size=Large]]
},
Domestic={
Small=[ Animal [name=Goat, type=Domestic, size=Small],
Animal [name=Dog, type=Domestic, size=Small]],
Large=[Animal [name=Cow, type=Domestic, size=Large]]
}
}
Here the result map is having animal type as a key then value as a another map, the second value map has size as a key and then List<Animal> as a value.