实现Java List多属性分组的步骤

1. 准备数据

首先,我们需要准备一些数据,用于进行多属性分组。假设我们有一个包含学生信息的类Student,其中包含学生的姓名、年龄和性别三个属性。我们可以创建一个包含多个Student对象的List集合。下面是一个示例代码:

List<Student> studentList = new ArrayList<>();

studentList.add(new Student("张三", 18, "男"));
studentList.add(new Student("李四", 19, "女"));
studentList.add(new Student("王五", 18, "男"));
studentList.add(new Student("赵六", 19, "女"));
studentList.add(new Student("钱七", 18, "男"));

2. 创建分组规则

接下来,我们需要定义一个分组规则,以确定如何根据多个属性来进行分组。在本例中,我们将按照年龄和性别两个属性进行分组。我们可以使用Java 8引入的Collectors.groupingBy方法来实现分组。下面是一个示例代码:

Map<String, Map<Integer, List<Student>>> groupedStudents = studentList.stream()
        .collect(Collectors.groupingBy(Student::getGender, 
                Collectors.groupingBy(Student::getAge)));

在上面的代码中,我们首先使用stream()方法将studentList转换为一个流,然后使用Collectors.groupingBy方法进行分组。我们使用Student::getGender作为第一个分组属性,将学生对象按照性别分组。然后,我们使用Collectors.groupingBy方法的嵌套形式,使用Student::getAge作为第二个分组属性,将学生对象按照年龄再次分组。最终,我们得到一个Map对象groupedStudents,其中包含了按照性别和年龄进行分组的结果。

3. 遍历分组结果

最后,我们可以遍历分组结果,以查看每个分组的内容。我们可以使用MapentrySet()方法获取分组结果的Set视图,然后使用增强型for循环进行遍历。下面是一个示例代码:

for (Map.Entry<String, Map<Integer, List<Student>>> genderEntry : groupedStudents.entrySet()) {
    String gender = genderEntry.getKey();
    Map<Integer, List<Student>> ageGroup = genderEntry.getValue();
    
    // 输出性别信息
    System.out.println("性别: " + gender);
    
    for (Map.Entry<Integer, List<Student>> ageEntry : ageGroup.entrySet()) {
        int age = ageEntry.getKey();
        List<Student> students = ageEntry.getValue();
        
        // 输出年龄信息
        System.out.println("年龄: " + age);
        
        // 输出学生信息
        for (Student student : students) {
            System.out.println(student.getName());
        }
    }
}

在上面的代码中,我们首先使用entrySet()方法获取了groupedStudents分组结果的Set视图。然后,使用两层增强型for循环分别遍历性别和年龄的分组。在内部循环中,我们输出了性别、年龄和学生姓名的信息。

完整代码示例

下面是一个完整的代码示例,将上述步骤整合在一起:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();

        studentList.add(new Student("张三", 18, "男"));
        studentList.add(new Student("李四", 19, "女"));
        studentList.add(new Student("王五", 18, "男"));
        studentList.add(new Student("赵六", 19, "女"));
        studentList.add(new Student("钱七", 18, "男"));

        Map<String, Map<Integer, List<Student>>> groupedStudents = studentList.stream()
                .collect(Collectors.groupingBy(Student::getGender,
                        Collectors.groupingBy(Student::getAge)));

        for (Map.Entry<String, Map<Integer, List<Student>>> genderEntry : groupedStudents.entrySet()) {
            String gender = genderEntry.getKey();
            Map<Integer, List<Student>> ageGroup = genderEntry.getValue();

            // 输出性别信息
            System.out.println("性别: " + gender);

            for (Map.Entry<Integer, List