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
You can do it by chaining two groupingBy
Collector
s 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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With