Muhammad Ramahy Muhammad Ramahy - 4 months ago 20
Java Question

convert list of object into a map of <String,Map<String,Integer>> java8 streams

hello I have a list of objects my object have three fields

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


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


that is like this:
{x1:{y1:z1,y2:z2,y3:z3},x2{y4:z4,y5:z5}}
format I want to do this in Java 8 which I think I am relatively new to it.

I have 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)))));


this does not even compile. help is much appreciated

Answer

You can do it by chaining two groupingBy Collectors 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 got the logic you wanted right.

When adding to the input List the following :

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 an output Map of :

{A={B=25, C=17}, B={C=10}}