
本文详细阐述了如何使用Java 8 Stream API处理复杂数据转换,包括对`Person`对象列表进行多条件过滤、根据日期月份和事件类型进行分组,并最终计算每个分组的总数。教程通过构建复合键、链式调用Stream操作,展示了从原始数据到结构化结果的完整流程。
在现代Java应用开发中,数据处理是核心任务之一。Java 8引入的Stream API极大地简化了集合操作,提供了声明式、函数式编程风格来处理数据。本教程将深入探讨如何利用Stream API实现一个常见的数据转换场景:从一个Person对象集合中,根据特定条件过滤数据,然后按事件发生的月份和类型进行分组,并最终统计每个分组的记录总数。
首先,我们需要定义涉及到的数据模型。Person类代表原始数据,包含人员ID、姓名、事件类型和事件日期等信息。State枚举用于表示事件类型(如JOIN或EXIT)。DTO类是最终输出结果的结构,包含月份、事件类型和总人数。为了实现多条件分组,我们还需要一个复合键类,这里我们使用MonthState。
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Comparator;
import java.util.stream.Collectors;
// 事件类型枚举
public enum State {
JOIN,
EXIT;
}
// 原始数据模型
public class Person {
private String id;
private String name;
private String surname;
private State event; // JOIN, EXIT
private Object value; // 示例中未使用,可根据实际需求调整
private LocalDate eventDate;
public Person(String id, String name, String surname, State event, LocalDate eventDate) {
this.id = id;
this.name = name;
this.surname = surname;
this.event = event;
this.eventDate = eventDate;
}
// Getters
public String getId() { return id; }
public State getEvent() { return event; }
public LocalDate getEventDate() { return eventDate; }
@Override
public String toString() {
return "Person{" + "id='" + id + '\'' + ", event=" + event + ", eventDate=" + eventDate + '}';
}
}
// 最终输出数据模型
public class DTO {
private int month;
private State info;
private int totalEmployees;
public DTO(int month, State info, int totalEmployees) {
this.month = month;
this.info = info;
this.totalEmployees = totalEmployees;
}
// Getters
public int getMonth() { return month; }
public State getInfo() { return info; }
public int getTotalEmployees() { return totalEmployees; }
@Override
public String toString() {
return "DTO{" + "month=" + month + ", info=" + info + ", totalEmployees=" + totalEmployees + '}';
}
}
// 用于分组的复合键(Java 16+ 可使用 record)
public record MonthState(int month, State info) {}
// 对于Java 8-15,可以使用普通类实现复合键,需要重写equals()和hashCode()
/*
public class MonthState {
private final int month;
private final State info;
public MonthState(int month, State info) {
this.month = month;
this.info = info;
}
public int getMonth() { return month; }
public State getInfo() { return info; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MonthState that = (MonthState) o;
return month == that.month && info == that.info;
}
@Override
public int hashCode() {
return Objects.hash(month, info);
}
}
*/我们的目标是从一个Map<String, List<Person>>类型的数据源(其中键是pId,值是该ID对应的Person对象列表)中,生成一个List<DTO>。这个过程将涉及以下Stream操作:
立即学习“Java免费学习笔记(深入)”;
下面是实现上述逻辑的Java Stream代码:
public class StreamProcessingExample {
public static void main(String[] args) {
// 示例数据初始化
Map<String, List<Person>> personListById = Map.of(
"per1", List.of(new Person("per1", "Alice", "Smith", State.JOIN, LocalDate.of(2022, 1, 10))),
"per2", List.of(new Person("per2", "Bob", "Johnson", State.JOIN, LocalDate.of(2022, 1, 10))),
"per3", List.of(
new Person("per3", "Charlie", "Brown", State.EXIT, LocalDate.of(2022, 1, 10)),
new Person("per3", "Charlie", "Brown", State.EXIT, LocalDate.of(2022, 2, 10))
),
"per4", List.of(new Person("per4", "David", "Miller", State.JOIN, LocalDate.of(2022, 3, 10)))
);
List<DTO> result = personListById.values().stream()
// 1. 扁平化:将 Map 的值(List<Person>)扁平化为 Person 对象的流
.flatMap(List::stream)
// 2. 过滤:只保留 JOIN 或 EXIT 类型的事件
.filter(per -> per.getEvent() == State.EXIT || per.getEvent() == State.JOIN)
// 3. 分组与计数:
// - 使用 MonthState 作为复合键,根据事件日期月份和事件类型进行分组
// - 使用 Collectors.counting() 统计每个分组的元素数量
.collect(Collectors.groupingBy(
p -> new MonthState(p.getEventDate().getMonthValue(), p.getEvent()),
Collectors.counting()
))
// 4. 将 Map.Entry 流转换为 DTO 对象流
.entrySet().stream()
.map(e -> new DTO(e.getKey().month(), e.getKey().info(), (int) (long) e.getValue()))
// 5. 排序:根据月份对 DTO 列表进行排序
.sorted(Comparator.comparing(DTO::getMonth))
// 6. 收集:将结果收集为 List<DTO>
.toList(); // 或者 .collect(Collectors.toList());
// 打印结果
result.forEach(System.out::println);
/* 预期输出:
DTO{month=1, info=JOIN, totalEmployees=2}
DTO{month=1, info=EXIT, totalEmployees=1}
DTO{month=2, info=EXIT, totalEmployees=1}
DTO{month=3, info=JOIN, totalEmployees=1}
*/
}
}通过本教程,我们学习了如何利用Java Stream API的flatMap、filter、groupingBy、counting、map和sorted等操作,高效地处理复杂的数据转换需求。关键在于理解每个Stream操作的作用,并合理地组合它们以构建一个清晰、声明式的数据处理管道。特别是,当需要根据多个属性进行分组时,定义一个合适的复合键(如MonthState record或类)是至关重要的一步。这种函数式编程风格不仅使代码更简洁,也提高了其可读性和可维护性。
以上就是高效利用Java Stream API:多条件过滤、按月分组与聚合求和的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号