0

0

Java 8 Stream实现自定义对象多属性分组与聚合

DDD

DDD

发布时间:2025-10-20 09:35:01

|

494人浏览过

|

来源于php中文网

原创

Java 8 Stream实现自定义对象多属性分组与聚合

本文深入探讨如何使用java 8 stream api对自定义对象(如`student`)进行多属性(如`name`, `age`, `city`)分组,并对其他数值属性(如`salary`, `incentive`)进行聚合求和。我们将通过创建自定义键类和累加器,结合`collectors.groupingby`与`collector.of`,构建一个高效且可读性强的解决方案,以解决传统方法在处理复杂聚合逻辑时的局限性。

在现代Java应用开发中,数据处理和转换是常见的任务。尤其是在处理集合数据时,经常需要根据对象的某些属性进行分组,并对其他属性执行聚合操作。例如,我们有一个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
    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; }

    // 为了方便打印结果,重写toString
    @Override
    public String toString() {
        return "Student{" +
               "name='" + name + '\'' +
               ", age=" + age +
               ", city='" + city + '\'' +
               ", salary=" + salary +
               ", incentive=" + incentive +
               '}';
    }
}

给定一个Student列表,例如:

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)

期望的输出是:

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

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

在尝试使用Collectors.toMap进行聚合时,我们可能会遇到以下问题:

  1. AbstractMap.SimpleEntry只能包含两个元素,无法直接作为包含name, age, city三个属性的复合键。
  2. double是基本数据类型,不具备add()方法,应使用+运算符进行加法运算。

为了解决这些问题,我们需要更灵活的策略,即引入自定义键对象和自定义累加器。

解决方案:自定义键与累加器

为了实现多属性分组和聚合,我们将采取以下步骤:

  1. 创建自定义键类:用于封装分组依据的多个属性。
  2. 创建自定义累加器类:用于在分组过程中累加数值属性。
  3. 使用Collectors.groupingBy结合Collector.of:将上述自定义类集成到Stream操作中。

1. 定义自定义键类 NameAgeCity

为了将name、age和city组合成一个唯一的键,我们需要一个自定义类。这个类必须正确地重写equals()和hashCode()方法,以确保在Map中作为键时能够正确地识别和比较。

import java.util.Objects; // 导入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());
    }

    // 必须重写equals和hashCode以确保Map的正确行为
    @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);
    }

    @Override
    public String toString() {
        return "NameAgeCity{" +
               "name='" + name + '\'' +
               ", age=" + age +
               ", city='" + city + '\'' +
               '}';
    }
}

注意事项

LLaMA
LLaMA

Meta公司发布的下一代开源大型语言模型

下载
  • 对于Java 16及更高版本,可以使用record关键字来更简洁地定义此类,编译器会自动生成构造函数、getter、equals()和hashCode()。
  • equals()和hashCode()的正确实现对于Map操作至关重要。

2. 定义自定义累加器类 AggregatedValues

为了累加salary和incentive,我们需要一个可变的容器。这个容器不仅要存储累加后的值,还要能够处理单个Student的输入并与其他容器合并(在并行流中)。

import java.util.function.Consumer; // 导入Consumer接口

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

    // 无参构造函数,用于Collector的supplier
    public AggregatedValues() {
        this.salary = 0.0;
        this.incentive = 0.0;
    }

    // Getters
    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; }

    // 实现Consumer接口的accept方法,用于累加单个Student对象
    @Override
    public void accept(Student s) {
        // 首次接受Student时,初始化分组的name, age, city
        // 假设同一个分组的所有Student这些属性都是相同的
        if (name == null) name = s.getName();
        if (age == 0) age = s.getAge(); // 注意:如果age可能为0,需要更严谨的判断
        if (city == null) city = s.getCity();

        this.salary += s.getSalary();
        this.incentive += s.getIncentive();
    }

    // 合并方法,用于并行流将多个AggregatedValues实例合并
    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);
    }

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

注意事项

  • accept()方法负责将单个Student的薪资和奖金累加到当前AggregatedValues实例中。
  • merge()方法在并行流中用于合并不同线程计算出的部分结果。
  • toStudent()方法是一个可选的“终结器”函数,用于将聚合结果转换回原始Student类型,如果最终列表需要是Student类型。

3. 使用Collectors.groupingBy与Collector.of进行聚合

现在,我们可以将上述自定义类集成到Stream操作中。我们将使用Collectors.groupingBy,它的第二个参数是一个“下游收集器”(downstream collector),这里我们将使用Collector.of来构建一个自定义的收集器。

Collector.of方法需要四个参数:

  • supplier:一个提供新的结果容器的工厂函数。
  • accumulator:一个将输入元素折叠到结果容器中的函数。
  • combiner:一个将两个结果容器合并的函数(主要用于并行流)。
  • finisher(可选):一个在累积完成后对结果容器执行最终转换的函数。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.function.Consumer; // 确保导入

public class StudentAggregator {

    // ... (Student, NameAgeCity, AggregatedValues 类定义同上,确保是静态内部类或独立类) ...

    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        // Java 8 兼容的添加元素方式
        Collections.addAll(students,
            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::from作为键映射函数
                Collectors.of(     // downstream collector: 自定义收集器
                    AggregatedValues::new,    // supplier: 提供新的AggregatedValues实例
                    AggregatedValues::accept, // accumulator: 将Student累加到AggregatedValues
                    AggregatedValues::merge,  // combiner: 合并两个AggregatedValues实例
                    AggregatedValues::toStudent // finisher: 将AggregatedValues转换为Student
                )
            ))
            .values() // 获取Map中所有AggregatedValues(已转换为Student)的集合
            .stream()
            .collect(Collectors.toList()); // 收集到List

        // 打印结果
        aggregatedStudents.forEach(System.out::println);
    }

    // 嵌套类定义 (为了示例完整性,这里再次包含,实际代码可独立定义)
    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 + '}';
        }
    }

    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 String getName() { return name; }
        public int getAge() { return age; }
        public String getCity() { return 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);
        }
    }

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

        public AggregatedValues() {
            this.salary = 0.0;
            this.incentive = 0.0;
        }
        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();
            if (city == null) city = s.getCity();
            salary += s.getSalary();
            incentive += s.getIncentive();
        }
        public AggregatedValues merge(AggregatedValues other) {
            salary += other.salary;
            incentive += other.incentive;
            return this;
        }
        public Student toStudent() {
            return new Student(name, age, city, salary, incentive);
        }
    }
}

输出结果

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}

总结与注意事项

通过上述方法,我们成功地利用Java 8 Stream API实现了自定义对象的多属性分组与聚合。

核心要点

  • 自定义键类 (NameAgeCity):当需要根据多个属性进行分组时,封装这些属性到一个自定义类中作为Map的键是最佳实践。务必正确重写equals()和hashCode()方法。
  • 自定义累加器 (AggregatedValues):对于复杂的聚合逻辑,尤其是需要累加多个字段时,创建一个可变的累加器类能提供清晰的结构和灵活的控制。
  • Collectors.groupingBy与Collector.of的组合:groupingBy提供分组能力,而Collector.of则提供了构建高度定制化聚合逻辑的强大机制,通过supplier、accumulator、combiner和finisher函数,可以处理几乎任何聚合需求。
  • 性能考量:对于数值类型(如double),直接使用基本类型的+运算符进行累加比使用BigDecimal等对象更高效,但如果涉及高精度计算,则需要考虑BigDecimal。
  • Java版本兼容性:本教程提供的解决方案完全兼容Java 8。对于更高版本,如Java 16+,record关键字可以简化键类的定义。

这种模式不仅适用于学生数据,也适用于任何需要根据多个属性进行分组并聚合其他属性的自定义对象场景,是Java 8 Stream API高级用法中的一个重要技巧。

热门AI工具

更多
DeepSeek
DeepSeek

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

豆包大模型
豆包大模型

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

WorkBuddy
WorkBuddy

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

腾讯元宝
腾讯元宝

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

文心一言
文心一言

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

讯飞写作
讯飞写作

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

即梦AI
即梦AI

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

ChatGPT
ChatGPT

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

相关专题

更多
数据类型有哪几种
数据类型有哪几种

数据类型有整型、浮点型、字符型、字符串型、布尔型、数组、结构体和枚举等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

338

2023.10.31

php数据类型
php数据类型

本专题整合了php数据类型相关内容,阅读专题下面的文章了解更多详细内容。

225

2025.10.31

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

138

2026.02.12

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1567

2023.10.24

Go语言中的运算符有哪些
Go语言中的运算符有哪些

Go语言中的运算符有:1、加法运算符;2、减法运算符;3、乘法运算符;4、除法运算符;5、取余运算符;6、比较运算符;7、位运算符;8、按位与运算符;9、按位或运算符;10、按位异或运算符等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

241

2024.02.23

php三元运算符用法
php三元运算符用法

本专题整合了php三元运算符相关教程,阅读专题下面的文章了解更多详细内容。

150

2025.10.17

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

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

334

2025.08.29

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

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

108

2025.10.23

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

76

2026.03.11

热门下载

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

精品课程

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

共23课时 | 4.4万人学习

C# 教程
C# 教程

共94课时 | 11.2万人学习

Java 教程
Java 教程

共578课时 | 81.4万人学习

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

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