使用Java 8中的Stream流的groupingBy方法和maxBy方法来实现流分组求最大值。

假设有一个Student类,包含name和score两个属性,现在要根据name对学生进行分组,并找出每个分组中score最高的学生。

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
                new Student("Tom", 80),
                new Student("Bob", 90),
                new Student("Alice", 70),
                new Student("Tom", 85),
                new Student("Bob", 95)
        );

        Map<String, Optional<Student>> maxScoreByGroup = students.stream()
                .collect(Collectors.groupingBy(Student::getName, Collectors.maxBy(Comparator.comparing(Student::getScore))));

        maxScoreByGroup.forEach((name, student) -> {
            System.out.println("Group: " + name + ", Max Score: " + student.orElse(new Student("", 0)).getScore());
        });
    }
}

class Student {
    private String name;
    private int score;

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

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

输出结果:

Group: Bob, Max Score: 95
Group: Alice, Max Score: 70
Group: Tom, Max Score: 85

在上述代码中,首先使用Collectors.groupingBy方法根据name属性对学生进行分组。然后,使用Collectors.maxBy方法对每个分组中的学生进行score属性的最大值求解。最后,遍历分组结果,打印每个分组的最大score值。

Java Stream 流分组求最大值:详细教程和代码示例

原文地址: https://www.cveoy.top/t/topic/qhpb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录