Java Stream流对集合进行分组操作

Java Stream流提供了groupingBy()方法,可以对集合进行分组操作。groupingBy()方法接受一个Function参数,用于指定分组的条件,并返回一个Collector对象,用于执行分组操作。

下面是一个示例:

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

public class GroupingExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个包含学生对象的集合
        List<Student> students = Arrays.asList(
                new Student("John", "Math"),
                new Student("Alice", "Science"),
                new Student("Bob", "Math"),
                new Student("Charlie", "Science"),
                new Student("David", "Math")
        );

        // 使用Stream流对学生集合进行专业(course)分组
        Map<String, List<Student>> groupedByCourse = students.stream()
                .collect(Collectors.groupingBy(Student::getCourse));

        // 打印分组结果
        for (Map.Entry<String, List<Student>> entry : groupedByCourse.entrySet()) {
    
    
            String course = entry.getKey();
            List<Student> studentsInCourse = entry.getValue();
            System.out.println("Course: " + course);
            for (Student student : studentsInCourse) {
    
    
                System.out.println("- " + student.getName());
            }
            System.out.println();
        }
    }
}

class Student {
    
    
    private String name;
    private String course;

    public Student(String name, String course) {
    
    
        this.name = name;
        this.course = course;
    }

    public String getName() {
    
    
        return name;
    }

    public String getCourse() {
    
    
        return course;
    }
}

运行以上代码,将输出以下结果:

Course: Math
- John
- Bob
- David

Course: Science
- Alice
- Charlie

在示例中,我们创建了一个包含学生对象的集合students。然后,我们使用stream()方法将集合转换为Stream流,并使用groupingBy()方法对学生集合进行分组,按照学生的专业(course)进行分组。分组结果存储在一个Map<String, List<Student>>对象中,其中键是专业名,值是对应专业的学生列表。

猜你喜欢

转载自blog.csdn.net/kkwyting/article/details/133426583