Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 668
Muhammad Bekette Avatar asked Jul 31 '16 17:07

Muhammad Bekette


1 Answers

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}}
like image 158
Eran Avatar answered Oct 03 '22 08:10

Eran