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 + '\'' +
               '}';
    }
}

注意事项

AiBiao.cn
AiBiao.cn

一句话自动生成图表

下载
  • 对于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 {
    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 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 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 {
        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高级用法中的一个重要技巧。

相关专题

更多
java
java

Java是一个通用术语,用于表示Java软件及其组件,包括“Java运行时环境 (JRE)”、“Java虚拟机 (JVM)”以及“插件”。php中文网还为大家带了Java相关下载资源、相关课程以及相关文章等内容,供大家免费下载使用。

841

2023.06.15

java正则表达式语法
java正则表达式语法

java正则表达式语法是一种模式匹配工具,它非常有用,可以在处理文本和字符串时快速地查找、替换、验证和提取特定的模式和数据。本专题提供java正则表达式语法的相关文章、下载和专题,供大家免费下载体验。

742

2023.07.05

java自学难吗
java自学难吗

Java自学并不难。Java语言相对于其他一些编程语言而言,有着较为简洁和易读的语法,本专题为大家提供java自学难吗相关的文章,大家可以免费体验。

738

2023.07.31

java配置jdk环境变量
java配置jdk环境变量

Java是一种广泛使用的高级编程语言,用于开发各种类型的应用程序。为了能够在计算机上正确运行和编译Java代码,需要正确配置Java Development Kit(JDK)环境变量。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

397

2023.08.01

java保留两位小数
java保留两位小数

Java是一种广泛应用于编程领域的高级编程语言。在Java中,保留两位小数是指在进行数值计算或输出时,限制小数部分只有两位有效数字,并将多余的位数进行四舍五入或截取。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

399

2023.08.02

java基本数据类型
java基本数据类型

java基本数据类型有:1、byte;2、short;3、int;4、long;5、float;6、double;7、char;8、boolean。本专题为大家提供java基本数据类型的相关的文章、下载、课程内容,供大家免费下载体验。

446

2023.08.02

java有什么用
java有什么用

java可以开发应用程序、移动应用、Web应用、企业级应用、嵌入式系统等方面。本专题为大家提供java有什么用的相关的文章、下载、课程内容,供大家免费下载体验。

430

2023.08.02

java在线网站
java在线网站

Java在线网站是指提供Java编程学习、实践和交流平台的网络服务。近年来,随着Java语言在软件开发领域的广泛应用,越来越多的人对Java编程感兴趣,并希望能够通过在线网站来学习和提高自己的Java编程技能。php中文网给大家带来了相关的视频、教程以及文章,欢迎大家前来学习阅读和下载。

16926

2023.08.03

云朵浏览器入口合集
云朵浏览器入口合集

本专题整合了云朵浏览器入口合集,阅读专题下面的文章了解更多详细地址。

20

2026.01.20

热门下载

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

精品课程

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

共23课时 | 2.7万人学习

C# 教程
C# 教程

共94课时 | 7.2万人学习

Java 教程
Java 教程

共578课时 | 48.6万人学习

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

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