5

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

2
  • 3
    Please provide a sample input, is not clear how you get all those y's and z's out of a single x Commented Jul 31, 2016 at 17:48
  • You shouldn't re-use your stream like that, nor should you need too. I don't think you problem is a good match for Streams, as I think you are trying to take the first two elements and map them to MyObject.x and the third and forth elements and map them using the second elements x value. It might be possible with a custom collector, but you are manipulating a lot of state Commented Jul 31, 2016 at 17:48

1 Answer 1

7

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}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.