0

0

使用Java 8 Streams对自定义对象进行多属性分组与聚合列表生成

DDD

DDD

发布时间:2025-10-19 13:57:01

|

958人浏览过

|

来源于php中文网

原创

使用Java 8 Streams对自定义对象进行多属性分组与聚合列表生成

引言:自定义对象多属性分组与聚合的挑战

在数据处理中,我们经常需要对集合中的对象根据一个或多个属性进行分组,并对每个组内的某些数值属性进行汇总。例如,给定一个student对象列表,我们可能需要根据学生的姓名、年龄和城市进行分组,然后计算每个组内学生的总薪资和总奖金。

Student类的定义如下:

public class Student {
    private String name;
    private int age;
    private String city;
    private double salary;
    private double incentive;

    public Student(String name, int age, String city, double salary, double incentive) {
        this.name = name;
        this.age = age;
        this.city = city;
        this.salary = salary;
        this.incentive = incentive;
    }

    // Getters for all fields
    public String getName() { return name; }
    public int getAge() { return age; }
    public String getCity() { return city; }
    public double getSalary() { return salary; }
    public double getIncentive() { return incentive; }

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + ", city='" + city + "', salary=" + salary + ", incentive=" + incentive + "}";
    }
}

假设我们有以下学生数据:

Student("Raj",10,"Pune",10000,100)
Student("Raj",10,"Pune",20000,200)
Student("Raj",20,"Pune",10000,100)
Student("Ram",30,"Pune",10000,100)
Student("Ram",30,"Pune",30000,300)
Student("Seema",10,"Pune",10000,100)

我们的目标是得到以下聚合结果:

Student("Raj",10,"Pune",30000,300) // "Raj", 10, "Pune" 的薪资和奖金合计
Student("Raj",20,"Pune",10000,100)
Student("Ram",30,"Pune",40000,400) // "Ram", 30, "Pune" 的薪资和奖金合计
Student("Seema",10,"Pune",10000,100)

直接使用Collectors.toMap尝试将多个属性作为键时,可能会遇到编译错误,因为AbstractMap.SimpleEntry只支持两个键值对。因此,我们需要一种更灵活的方式来定义复合键并执行自定义的聚合逻辑。

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

方案一:定义复合键对象

为了将多个属性(name, age, city)作为分组的依据,我们需要创建一个自定义的复合键类。这个类将封装所有用于分组的属性,并且必须正确实现equals()和hashCode()方法,以确保在Map中作为键时能够正确地进行比较和查找。

对于Java 8环境,我们可以定义一个静态内部类NameAgeCity:

import java.util.Objects;

public static class NameAgeCity {
    private String name;
    private int age;
    private String city;

    public NameAgeCity(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }

    // Getters
    public String getName() { return name; }
    public int getAge() { return age; }
    public String getCity() { return city; }

    // 静态工厂方法,方便从Student对象创建
    public static NameAgeCity from(Student s) {
        return new NameAgeCity(s.getName(), s.getAge(), s.getCity());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        NameAgeCity that = (NameAgeCity) o;
        return age == that.age &&
               Objects.equals(name, that.name) &&
               Objects.equals(city, that.city);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, city);
    }
}

注意事项:

  • equals()和hashCode()方法的正确实现是至关重要的。hashCode()应返回一个基于所有关键属性的哈希值,而equals()应比较所有关键属性是否相等。这是Map正确识别相同键的基础。
  • 对于Java 16及更高版本,可以使用record关键字更简洁地定义此类,编译器会自动生成构造函数、getter、equals()和hashCode()。

方案二:创建自定义聚合器

为了对每个分组内的salary和incentive进行累加,我们需要一个可变的容器来存储中间的聚合结果。这个容器不仅要能累加数值,还要能处理并行流的合并操作。我们可以创建一个AggregatedValues类来实现这个功能。

import java.util.function.Consumer;

public class AggregatedValues implements Consumer<Student> {
    private String name;
    private int age;
    private String city;
    private double salary;
    private double incentive;

    // 无参构造函数,用于Collector的supplier
    public AggregatedValues() {
        // 默认初始化,salary和incentive默认为0.0
    }

    // Getters for aggregated values
    public String getName() { return name; }
    public int getAge() { return age; }
    public String getCity() { return city; }
    public double getSalary() { return salary; }
    public double getIncentive() { return incentive; }

    @Override
    public void accept(Student s) {
        // 首次接受学生时,初始化分组的标识属性
        if (name == null) name = s.getName();
        if (age == 0) age = s.getAge(); // 注意:如果age可能为0,需要更严谨的判断
        if (city == null) city = s.getCity();

        // 累加薪资和奖金
        salary += s.getSalary();
        incentive += s.getIncentive();
    }

    // 用于并行流合并的combiner
    public AggregatedValues merge(AggregatedValues other) {
        this.salary += other.salary;
        this.incentive += other.incentive;
        return this;
    }

    // 可选:将聚合结果转换回Student对象
    public Student toStudent() {
        return new Student(name, age, city, salary, incentive);
    }
}

AggregatedValues类的作用:

AIBox 一站式AI创作平台
AIBox 一站式AI创作平台

AIBox365一站式AI创作平台,支持ChatGPT、GPT4、Claue3、Gemini、Midjourney等国内外大模型

下载
  • accept(Student s) (Accumulator): 当Stream处理一个Student对象时,这个方法会被调用,负责将该学生的数据累加到当前的AggregatedValues实例中。它还会初始化分组的标识属性(name, age, city),因为同一个分组内的这些属性是相同的。
  • merge(AggregatedValues other) (Combiner): 在并行流处理中,不同的线程可能会生成各自的AggregatedValues部分结果。merge方法负责将这些部分结果合并成一个最终结果。

使用 Collectors.groupingBy 和 Collector.of 进行聚合

现在,我们已经有了复合键类NameAgeCity和聚合器AggregatedValues,可以利用Java 8的Stream API来执行分组和聚合操作。我们将使用Collectors.groupingBy,并结合Collector.of来构建一个自定义的下游收集器。

Collector.of允许我们精确控制聚合过程的四个阶段:

  1. supplier: 创建一个新的结果容器(在这里是AggregatedValues实例)。
  2. accumulator: 将单个输入元素(Student)累加到结果容器中。
  3. combiner: 合并两个结果容器(在并行流中)。
  4. finisher (可选): 对最终结果容器进行转换,生成最终的输出类型。

完整的实现代码如下:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.function.Consumer;

public class StudentAggregator {

    // Student 类定义 (同上)
    public static class Student {
        private String name;
        private int age;
        private String city;
        private double salary;
        private double incentive;

        public Student(String name, int age, String city, double salary, double incentive) {
            this.name = name;
            this.age = age;
            this.city = city;
            this.salary = salary;
            this.incentive = incentive;
        }

        public String getName() { return name; }
        public int getAge() { return age; }
        public String getCity() { return city; }
        public double getSalary() { return salary; }
        public double getIncentive() { return incentive; }

        @Override
        public String toString() {
            return "Student{name='" + name + "', age=" + age + ", city='" + city + "', salary=" + salary + ", incentive=" + incentive + "}";
        }
    }

    // NameAgeCity 复合键类定义 (同上)
    public static class NameAgeCity {
        private String name;
        private int age;
        private String city;

        public NameAgeCity(String name, int age, String city) {
            this.name = name;
            this.age = age;
            this.city = city;
        }

        public static NameAgeCity from(Student s) {
            return new NameAgeCity(s.getName(), s.getAge(), s.getCity());
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            NameAgeCity that = (NameAgeCity) o;
            return age == that.age &&
                   Objects.equals(name, that.name) &&
                   Objects.equals(city, that.city);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, age, city);
        }
    }

    // AggregatedValues 聚合器类定义 (同上)
    public static class AggregatedValues implements Consumer<Student> {
        private String name;
        private int age;
        private String city;
        private double salary;
        private double incentive;

        public AggregatedValues() {} // 默认构造函数

        public String getName() { return name; }
        public int getAge() { return age; }
        public String getCity() { return city; }
        public double getSalary() { return salary; }
        public double getIncentive() { return incentive; }

        @Override
        public void accept(Student s) {
            if (name == null) name = s.getName();
            if (age == 0) age = s.getAge(); // 假设age不会是0作为有效值,否则需要更严谨判断
            if (city == null) city = s.getCity();
            salary += s.getSalary();
            incentive += s.getIncentive();
        }

        public AggregatedValues merge(AggregatedValues other) {
            this.salary += other.salary;
            this.incentive += other.incentive;
            return this;
        }

        public Student toStudent() {
            return new Student(name, age, city, salary, incentive);
        }
    }

    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Collections.addAll(students, // Java 8 使用 Collections.addAll 或 Arrays.asList
            new Student("Raj", 10, "Pune", 10000, 100),
            new Student("Raj", 10, "Pune", 20000, 200),
            new Student("Raj", 20, "Pune", 10000, 100),
            new Student("Ram", 30, "Pune", 10000, 100),
            new Student("Ram", 30, "Pune", 30000, 300),
            new Student("Seema", 10, "Pune", 10000, 100)
        );

        List<Student> aggregatedStudents = students.stream()
            .collect(Collectors.groupingBy(
                NameAgeCity::from, // keyMapper: 使用NameAgeCity作为分组键
                Collectors.reducing( // 下游收集器: 使用reducing进行聚合
                    new AggregatedValues(), // identity: 初始值
                    (agg, student) -> { // accumulator: 将学生数据累加到AggregatedValues
                        agg.accept(student);
                        return agg;
                    },
                    (agg1, agg2) -> agg1.merge(agg2) // combiner: 合并两个AggregatedValues
                )
            ))
            .values().stream() // 获取Map中的所有AggregatedValues
            .map(AggregatedValues::toStudent) // finisher: 将AggregatedValues转换为Student
            .collect(Collectors.toList()); // 收集为List

        aggregatedStudents.forEach(System.out::println);
    }
}

输出结果:

Student{name='Raj', age=20, city='Pune', salary=10000.0, incentive=100.0}
Student{name='Raj', age=10, city='Pune', salary=30000.0, incentive=300.0}
Student{name='Ram', age=30, city='Pune', salary=40000.0, incentive=400.0}
Student{name='Seema', age=10, city='Pune', salary=10000.0, incentive=100.0}

代码解析:

  1. students.stream(): 创建一个学生对象的Stream。
  2. collect(Collectors.groupingBy(...)): 这是核心的分组操作。
    • NameAgeCity::from: 作为keyMapper,它将每个Student对象映射成一个NameAgeCity实例作为分组的键。
    • Collectors.reducing(...): 作为下游收集器,它负责对每个分组内的元素进行聚合。
      • new AggregatedValues(): identity,提供每个分组的初始聚合器实例。
      • (agg, student) -> { agg.accept(student); return agg; }: accumulator,将每个Student累加到AggregatedValues中。
      • (agg1, agg2) -> agg1.merge(agg2): combiner,合并两个AggregatedValues实例。
  3. .values().stream(): groupingBy返回一个Map<NameAgeCity, AggregatedValues>。我们只关心聚合后的值,所以获取Map的所有值并再次转换为Stream。
  4. .map(AggregatedValues::toStudent): finisher阶段,将每个AggregatedValues实例转换回我们期望的Student对象。
  5. .collect(Collectors.toList()): 将最终的Student对象Stream收集到一个List中。

总结与注意事项

通过以上方法,我们成功地解决了Java 8中自定义对象多属性分组与聚合的问题。这种模式的优势在于:

  • 清晰的职责分离: NameAgeCity负责定义分组键的逻辑,AggregatedValues负责聚合逻辑,Student保持其原始数据结构。
  • 可维护性高: 避免了在Collectors.toMap中使用复杂的匿名函数或临时数据结构作为键。
  • 灵活性强: Collector.of提供了高度的灵活性,可以处理各种复杂的聚合需求。
  • Java 8兼容: 所有代码都可以在Java 8环境下运行。

注意事项:

  • equals()和hashCode()的重要性: 任何用作Map键的自定义对象都必须正确实现这两个方法。
  • 浮点数精度: double类型的直接相加可能存在精度问题。如果对精度有严格要求,应考虑使用BigDecimal进行金融计算或其他需要高精度计算的场景。
  • AggregatedValues的初始化: 在AggregatedValues的accept方法中,我们假设age不会是0作为有效分组属性。如果age可能为0,需要更严谨的逻辑来判断何时初始化name、age、city,例如通过检查name == null作为首次接收的标志。
  • 下游收集器选择: 示例中使用了Collectors.reducing结合AggregatedValues。另一种常见且更直接的方式是使用Collector.of作为groupingBy的下游收集器,如下所示,其效果是相同的:
// 使用 Collector.of 作为下游收集器
List<Student> aggregatedStudents = students.stream()
    .collect(Collectors.groupingBy(
        NameAgeCity::from,              // keyMapper
        java.util.stream.Collector.of(  // custom collector
            AggregatedValues::new,      // supplier
            AggregatedValues::accept,   // accumulator
            AggregatedValues::merge,    // combiner
            AggregatedValues::toStudent // finisherFunction
        )
    ))
    .values().stream()
    .collect(Collectors.toList());

这种方式更加简洁,直接将AggregatedValues的toStudent方法作为finisherFunction,避免了额外的map操作。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
c语言中null和NULL的区别
c语言中null和NULL的区别

c语言中null和NULL的区别是:null是C语言中的一个宏定义,通常用来表示一个空指针,可以用于初始化指针变量,或者在条件语句中判断指针是否为空;NULL是C语言中的一个预定义常量,通常用来表示一个空值,用于表示一个空的指针、空的指针数组或者空的结构体指针。

254

2023.09.22

java中null的用法
java中null的用法

在Java中,null表示一个引用类型的变量不指向任何对象。可以将null赋值给任何引用类型的变量,包括类、接口、数组、字符串等。想了解更多null的相关内容,可以阅读本专题下面的文章。

1089

2024.03.01

c++怎么把double转成int
c++怎么把double转成int

本专题整合了 c++ double相关教程,阅读专题下面的文章了解更多详细内容。

335

2025.08.29

C++中int、float和double的区别
C++中int、float和double的区别

本专题整合了c++中int和double的区别,阅读专题下面的文章了解更多详细内容。

108

2025.10.23

treenode的用法
treenode的用法

​在计算机编程领域,TreeNode是一种常见的数据结构,通常用于构建树形结构。在不同的编程语言中,TreeNode可能有不同的实现方式和用法,通常用于表示树的节点信息。更多关于treenode相关问题详情请看本专题下面的文章。php中文网欢迎大家前来学习。

550

2023.12.01

C++ 高效算法与数据结构
C++ 高效算法与数据结构

本专题讲解 C++ 中常用算法与数据结构的实现与优化,涵盖排序算法(快速排序、归并排序)、查找算法、图算法、动态规划、贪心算法等,并结合实际案例分析如何选择最优算法来提高程序效率。通过深入理解数据结构(链表、树、堆、哈希表等),帮助开发者提升 在复杂应用中的算法设计与性能优化能力。

30

2025.12.22

深入理解算法:高效算法与数据结构专题
深入理解算法:高效算法与数据结构专题

本专题专注于算法与数据结构的核心概念,适合想深入理解并提升编程能力的开发者。专题内容包括常见数据结构的实现与应用,如数组、链表、栈、队列、哈希表、树、图等;以及高效的排序算法、搜索算法、动态规划等经典算法。通过详细的讲解与复杂度分析,帮助开发者不仅能熟练运用这些基础知识,还能在实际编程中优化性能,提高代码的执行效率。本专题适合准备面试的开发者,也适合希望提高算法思维的编程爱好者。

45

2026.01.06

线程和进程的区别
线程和进程的区别

线程和进程的区别:线程是进程的一部分,用于实现并发和并行操作,而线程共享进程的资源,通信更方便快捷,切换开销较小。本专题为大家提供线程和进程区别相关的各种文章、以及下载和课程。

766

2023.08.10

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 4.4万人学习

C# 教程
C# 教程

共94课时 | 11.3万人学习

Java 教程
Java 教程

共578课时 | 81.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号