
在数据处理中,我们经常需要对集合中的对象根据一个或多个属性进行分组,并对每个组内的某些数值属性进行汇总。例如,给定一个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);
}
}注意事项:
为了对每个分组内的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类的作用:
现在,我们已经有了复合键类NameAgeCity和聚合器AggregatedValues,可以利用Java 8的Stream API来执行分组和聚合操作。我们将使用Collectors.groupingBy,并结合Collector.of来构建一个自定义的下游收集器。
Collector.of允许我们精确控制聚合过程的四个阶段:
完整的实现代码如下:
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}代码解析:
通过以上方法,我们成功地解决了Java 8中自定义对象多属性分组与聚合的问题。这种模式的优势在于:
注意事项:
// 使用 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号