在Java中,使用Stream流进行多次分组可以通过多次调用Collectors.groupingBy
方法实现。每次调用groupingBy
方法都会将元素按照指定的分类条件进行分组。
import java.util.*;
import java.util.stream.Collectors;
public class StreamGroupingExample {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("Alice", 25, "Female"),
new Person("Bob", 30, "Male"),
new Person("Charlie", 35, "Male"),
new Person("Diana", 28, "Female"),
new Person("Eva", 25, "Female"),
new Person("Frank", 30, "Male")
);
// 第一次分组:按性别分组
Map<String, List<Person>> genderGroups = persons.stream()
.collect(Collectors.groupingBy(Person::getGender));
System.out.println("按性别分组结果:");
System.out.println(genderGroups);
// 第二次分组:在每个性别组内按年龄分组
Map<String, Map<Integer, List<Person>>> ageGroups = persons.stream()
.collect(Collectors.groupingBy(Person::getGender,
Collectors.groupingBy(Person::getAge)));
System.out.println("按性别和年龄分组结果:");
System.out.println(ageGroups);
}
static class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
= name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
@Override
public String toString() {
return name;
}
}
}
输出结果:
按性别分组结果:
{Female=[Alice, Diana, Eva], Male=[Bob, Charlie, Frank]}
按性别和年龄分组结果:
{Female={25=[Alice, Eva], 28=[Diana]}, Male={30=[Bob, Frank], 35=[Charlie]}}
首先按照性别对Person
对象进行分组。然后,在每个性别组内再按照年龄对Person
对象进行分组。通过多次使用Collectors.groupingBy
方法,我们实现了多次分组。