Java 8 中的多层分组通常使用 Collectors.groupingBy
方法来实现。以下是一个示例,演示如何在一个对象列表上进行多层分组:
假设我们有一个Person
类:
import java.util.ArrayList;
import java.util.List;
public class Person {
private String name;
private String city;
private int age;
public Person(String name, String city, int age) {
this.name = name;
this.city = city;
this.age = age;
}
public String getName() {
return name;
}
public String getCity() {
return city;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", city='" + city + '\'' +
", age=" + age +
'}';
}
}
然后,我们可以使用多层分组,按照城市和年龄进行分组:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MultiLevelGroupingExample {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", "New York", 25),
new Person("Bob", "New York", 30),
new Person("Charlie", "London", 35),
new Person("David", "London", 40),
new Person("Eva", "Paris", 25),
new Person("Frank", "Paris", 30)
);
// 多层分组:先按城市分组,再按年龄分组
Map<String, Map<Integer, List<Person>>> groupedByCityAndAge = people.stream()
.collect(Collectors.groupingBy(Person::getCity,
Collectors.groupingBy(Person::getAge)));
// 打印结果
groupedByCityAndAge.forEach((city, ageMap) -> {
System.out.println("City: " + city);
ageMap.forEach((age, persons) -> {
System.out.println(" Age: " + age);
persons.forEach(System.out::println);
});
});
}
}
这个例子中,people
列表按照城市和年龄进行了多层分组。Collectors.groupingBy
方法的嵌套使用允许我们按照不同的属性进行多层次的分组。