Convert a list of objects in the map <String, Map <String, Integer> java8 streams

hello I have a list of objects in which my object has three fields

class MyObject{ String x; String y; int z; //getters n setters } 

I need to convert this list to Map<String,Map<String,Integer>>

like this: {x1:{y1:z1,y2:z2,y3:z3},x2{y4:z4,y5:z5}} the format I want to do it in Java 8, which is, I think, is a relative newcomer.

I tried the following:

 Map<String,Map<String,Integer>> map=list.stream(). collect(Collectors. groupingBy(MyObject::getX,list.stream(). collect(Collectors.groupingBy(MyObject::getY, Collectors.summingInt(MyObject::getZ))))); 

it doesn't even compile. help is much appreciated

+5
source share
1 answer

You can do this by connecting two groupingBy Collector and one summingInt Collector :

 Map<String,Map<String,Integer>> map = list.stream() .collect(Collectors. groupingBy(MyObject::getX, Collectors.groupingBy(MyObject::getY, Collectors.summingInt(MyObject::getZ)))); 

I hope I have the logic you would like to receive.

When adding the following to the List input:

 list.add(new MyObject("A","B",10)); list.add(new MyObject("A","C",5)); list.add(new MyObject("A","B",15)); list.add(new MyObject("B","C",10)); list.add(new MyObject("A","C",12)); 

You get Map output from:

 {A={B=25, C=17}, B={C=10}} 
+7
source

All Articles