Marvy
Marvy

Reputation: 87

Java Stream : multiple grouping

I can group by one field but i want to group by both together

//persons grouped by gender
Map<String, Long> personsGroupedByGender = persons.stream().collect(Collectors.groupingBy(Person::getGender, Collectors.counting()));

//persons grouped by age
Map<Int, Long> personsGroupedByAge = persons.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));

//persons grouped by gender and age 

    ???

Upvotes: 2

Views: 2833

Answers (3)

gvashchenko
gvashchenko

Reputation: 1

import org.apache.commons.lang3.tuple.Pair;
Map<Pair<String, String>, Long> personsGroupedByGenderAge = persons.stream()
    .collect(Collectors.groupingBy(
         person -> Pair.of(person.getGender, person.getAge),
         Collectors.counting()));

Upvotes: 0

Eugene
Eugene

Reputation: 120978

You can group twice, the result will be what you expect, but in a slightly different wrapping.

persons.stream().collect(Collectors.groupingBy(Person::getGender,  
              Collectors.groupingBy(Person::getAge, Collectors.counting())));

Upvotes: 7

Joe C
Joe C

Reputation: 15714

My suggestion would be to create a helper class which represents your grouping key (gender and age, in this case), with appropriate equals and hashCode implementations. You can then create a mapper function from your Person to this key, and group by that.

Upvotes: 1

Related Questions