I have a list of pojos that I want to perform some grouping on. Something like:
public class Pojo {
private final Category category;
private final BigDecimal someValue;
}
public class Category {
private final String majorCategory;
private final String minorCategory;
}
I want a Map<String, Map<String, List<Pojo>>>
where the key is majorCategory
and the value is a Map
with key minorCategory
and values is a List
of Pojo
objects for said minorCategory
.
I intend to use Java 8 lambdas to achieve this. I can get the first level of grouping done with the following:
Map<String, Pojo> result = list
.stream()
.collect(groupingBy(p -> p.getCategory().getMajorCategory()));
How can I now group again on minorCategory
and get the Map<String, Map<String, List<Pojo>>>
I desire?
Update
The first answer provided is correct for the example provided initially, however I have since updated the question. Ruben's comment in the accepted answer, provides the final piece of the puzzle.
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL's GROUP BY clause.
As the grouping collector works on the stream of objects its collecting from it creates collections of stream objects corresponding to each of the 'group keys'. I.e. for every value of R there is a collection of objects all of which return that value of R when subjected to the classification function.
groupingBy(Pojo::getMajorCategory, groupingBy(Pojo::getMinorCategory))
should work, I think?
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