Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Java Stream API:高效分组并获取最大值映射_创想鸟

Java Stream API:高效分组并获取最大值映射

Java Stream API:高效分组并获取最大值映射

本文深入探讨如何利用java stream api,特别是collectors.tomap的强大功能,结合binaryoperator.maxby,以一种高度优化的方式,将对象列表(如学生成绩)按特定属性(如学生id)进行分组。目标是为每个分组选取出具有最大值的对象,并直接生成一个简洁的键值映射(如学生id到最高成绩对象),从而避免传统groupingby结合后续处理的复杂性。

在日常的Java开发中,我们经常会遇到需要处理对象集合的场景。一个常见的需求是,根据某个属性对集合中的对象进行分组,并在每个分组中选出具有特定“极值”(最大值或最小值)的对象。例如,给定一个StudentGrade对象的列表,我们希望获取每个学生的最高成绩,并将其组织成一个以学生ID为键,最高成绩对象为值的Map。

假设我们有如下的StudentGrade类定义:

import java.util.Date;public class StudentGrade {    int studentId;    double value; // 成绩值    Date date;    // 成绩记录日期    public StudentGrade(int studentId, double value, Date date) {        this.studentId = studentId;        this.value = value;        this.date = date;    }    public int getStudentId() {        return studentId;    }    public double getValue() {        return value;    }    public Date getDate() {        return date;    }    @Override    public String toString() {        return "StudentGrade{" +               "studentId=" + studentId +               ", value=" + value +               ", date=" + date +               '}';    }}

传统分组与筛选方式的局限性

一种直观但略显繁琐的方法是使用Collectors.groupingBy先按studentId分组,然后为每个分组收集最大值,最后再将结果转换为所需的Map。

import java.util.*;import java.util.stream.Collectors;import java.util.function.Function;public class GradeProcessor {    public Map getMaxGradeByStudentTraditional(List grades) {        // 步骤1: 使用 groupingBy 分组并获取每个学生的最大成绩(Optional)        Map<Integer, Optional> maxGradesOptional = grades.stream().collect(            Collectors.groupingBy(                StudentGrade::getStudentId,                Collectors.maxBy(Comparator.comparing(StudentGrade::getValue)))        );        // 步骤2: 遍历结果,处理 Optional 并构建最终的 Map        Map finalGrades = new HashMap();        maxGradesOptional.entrySet().forEach(entry -> {            entry.getValue().ifPresent(value -> finalGrades.put(entry.getKey(), value));        });        return finalGrades;    }}

上述方法虽然可行,但存在以下几点不足:

立即学习“Java免费学习笔记(深入)”;

中间状态: maxGradesOptional是一个Map<Integer, Optional>,引入了Optional作为中间层,增加了处理的复杂性。二次迭代: 需要对maxGradesOptional进行二次迭代,才能将Optional解包并放入最终的Map中。代码冗余: 初始化HashMap和手动put操作使得代码不够简洁。

利用 Collectors.toMap 实现高效分组与最大值筛选

Java Stream API提供了一个更优雅、更高效的解决方案,即使用Collectors.toMap的三参数重载方法。这个方法允许我们定义如何处理键冲突(即当多个元素映射到同一个键时)。这正是我们解决“获取每个分组最大值”问题的关键。

Collectors.toMap的三个参数分别是:

博思AIPPT 博思AIPPT

博思AIPPT来了,海量PPT模板任选,零基础也能快速用AI制作PPT。

博思AIPPT 117 查看详情 博思AIPPT keyMapper: 一个Function,用于从输入元素中提取Map的键。valueMapper: 一个Function,用于从输入元素中提取Map的值。mergeFunction: 一个BinaryOperator,用于处理当多个元素映射到同一个键时如何合并它们。

通过巧妙地使用mergeFunction,我们可以直接在流处理过程中解决键冲突,并选择我们需要的最大值对象。

import java.util.*;import java.util.stream.Collectors;import java.util.function.Function;import java.util.function.BinaryOperator;public class GradeProcessor {    public Map getMaxGradeByStudentOptimized(List grades) {        return grades.stream()                .collect(Collectors.toMap(                    StudentGrade::getStudentId, // keyMapper: 以 studentId 作为 Map 的键                    Function.identity(),        // valueMapper: 原始 StudentGrade 对象作为 Map 的值                    BinaryOperator.maxBy(Comparator.comparing(StudentGrade::getValue)) // mergeFunction: 键冲突时,选择 value 较大的 StudentGrade                ));    }    // 示例用法    public static void main(String[] args) {        List grades = Arrays.asList(            new StudentGrade(1, 85.0, new Date()),            new StudentGrade(2, 92.5, new Date()),            new StudentGrade(1, 90.0, new Date()), // 学生1的更高成绩            new StudentGrade(3, 78.0, new Date()),            new StudentGrade(2, 88.0, new Date())  // 学生2的较低成绩        );        GradeProcessor processor = new GradeProcessor();        Map maxGrades = processor.getMaxGradeByStudentOptimized(grades);        maxGrades.forEach((studentId, grade) ->            System.out.println("Student ID: " + studentId + ", Max Grade: " + grade.getValue())        );        /*         * 预期输出:         * Student ID: 1, Max Grade: 90.0         * Student ID: 2, Max Grade: 92.5         * Student ID: 3, Max Grade: 78.0         */    }}

深入理解 mergeFunction

mergeFunction (BinaryOperator) 接收两个参数(T oldVal, T newVal),它们是映射到同一个键的两个值。它的职责是返回其中一个作为最终的值,或者根据这两个值计算出一个新的值。

在本例中,BinaryOperator.maxBy(Comparator.comparing(StudentGrade::getValue)) 是核心。

Comparator.comparing(StudentGrade::getValue) 创建了一个比较器,用于根据StudentGrade对象的value属性进行比较。BinaryOperator.maxBy() 则利用这个比较器,在两个冲突的StudentGrade对象中,选择value较大的那个。

当Collectors.toMap处理流中的元素时,如果遇到一个studentId已经存在于Map中的StudentGrade对象,它会调用mergeFunction。mergeFunction会比较当前Map中已有的StudentGrade(oldVal)和新来的StudentGrade(newVal),然后返回两者中成绩更高的那个,从而确保Map中每个学生ID对应的是其最高成绩。

优化方案的优势

使用Collectors.toMap结合BinaryOperator.maxBy的方法具有显著优势:

代码简洁性: 将分组、筛选和映射的逻辑整合到单个collect操作中,代码更加紧凑和易读。避免中间对象: 直接生成Map,无需中间的Optional包装或额外的HashMap初始化。性能提升: 在单次遍历流的过程中完成所有操作,减少了迭代次数和潜在的内存开销。函数式编程风格: 更好地体现了Java Stream API的函数式编程思想。

注意事项

空列表处理: 如果输入的grades列表为空,getMaxGradeByStudentOptimized方法将返回一个空的Map,这是符合预期的行为。null 值处理: 如果StudentGrade的studentId或value可能为null,需要额外处理。例如,Comparator.comparing在比较null值时可能会抛出NullPointerException。可以通过Comparator.nullsFirst()或nullsLast()来处理,或者在流处理前过滤掉null元素。非唯一键值: toMap的keyMapper必须能够生成唯一的键,否则需要提供mergeFunction来处理冲突。如果未提供mergeFunction而出现键冲突,IllegalStateException将被抛出。

总结

Java Stream API提供了一套强大而灵活的工具来处理集合数据。通过熟练运用Collectors.toMap的三参数重载方法,并结合合适的BinaryOperator(如maxBy或minBy),我们能够以高度优化的方式实现复杂的数据转换和筛选逻辑。这种方法不仅使代码更加简洁、可读,而且在处理大规模数据时也能提供更好的性能表现,是现代Java开发中值得推荐的实践。

以上就是Java Stream API:高效分组并获取最大值映射的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/961527.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
电脑壁纸下载不了。怎么办?
上一篇 2025年12月1日 18:47:07
MySQL插入唯一约束数据怎么办_MySQL唯一约束数据插入处理
下一篇 2025年12月1日 18:47:11

相关推荐

发表回复

登录后才能评论
关注微信