2

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 

    ???
3
  • .getAge() returns a String? Commented May 10, 2017 at 19:56
  • I corrrected that one Commented May 11, 2017 at 6:28
  • @Marvy may be Map<Integer, Long>? Probably a typo. Commented May 11, 2017 at 6:46

3 Answers 3

7

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())));
Sign up to request clarification or add additional context in comments.

1 Comment

@Marvy if it helped might as well accept it. meta.stackexchange.com/questions/5234/…
1

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.

1 Comment

that's not a bad suggestion overall and while I did not downvote - you probably got it because you should have showed some code also...
0
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()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.