简体   繁体   English

Java Stream:多个分组

[英]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 

    ???

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())));

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.我的建议是创建一个辅助类,它代表您的分组键(在本例中为性别和年龄),并具有适当的equalshashCode实现。 You can then create a mapper function from your Person to this key, and group by that.然后,您可以创建从Person到此键的映射器函数,并按此分组。

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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM