Java 8 lambdas grouping by multiple fields

21.3k views Asked by At

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.

1

There are 1 answers

3
Louis Wasserman On BEST ANSWER
groupingBy(Pojo::getMajorCategory, groupingBy(Pojo::getMinorCategory))

should work, I think?