首页 > Java > java教程 > 正文

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

DDD
发布: 2025-10-19 13:57:01
原创
939人浏览过

使用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类的作用:

标书对比王
标书对比王

标书对比王是一款标书查重工具,支持多份投标文件两两相互比对,重复内容高亮标记,可快速定位重复内容原文所在位置,并可导出比对报告。

标书对比王 58
查看详情 标书对比王
  • 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操作。

以上就是使用Java 8 Streams对自定义对象进行多属性分组与聚合列表生成的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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