Reputation: 37034
I have a code like this:
class MyObject{
String division;
String subDivision;
Integer size;
public MyObject(String division, String subDivision, Integer size) {
this.division = division;
this.subDivision = subDivision;
this.size = size;
}
List<MyObject> list = Arrays.asList(new MyObject("A", "AA", 4),
new MyObject("A", "AB", 2),
new MyObject("A", "AC", 3),
new MyObject("B", "BA", 11),
new MyObject("B", "BB", 7),
new MyObject("C", "CA", 8));
Map<String, Map<String,Integer>> map
= list.stream().collect(Collectors.toMap(MyObject::getDivision), ...);
Could you help me to finish the code base ?
Upvotes: 0
Views: 128
Reputation: 4935
You could use groupingBy
which takes a classifier and a downstream collector. The classifier is used to create the outer map based on division
and then the downstream collector (toMap
) is used to generate the inner map:
list.stream()
.collect(Collectors.groupingBy(MyObject::getDivision,
Collectors.toMap(MyObject::getSubDivision, MyObject::getSize)));
Upvotes: 2