Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambdas grouping by multiple fields

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.

like image 335
Robert Bain Avatar asked Jun 12 '15 16:06

Robert Bain


People also ask

How many types of streams does Java 8 have?

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.

How do you use groupingBy collectors?

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.

How is grouping function evaluated for collection?

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.


1 Answers

groupingBy(Pojo::getMajorCategory, groupingBy(Pojo::getMinorCategory))

should work, I think?

like image 185
Louis Wasserman Avatar answered Oct 23 '22 07:10

Louis Wasserman