
本文详细讲解如何利用java 8 streams api高效处理复杂数据聚合需求,包括多条件过滤、按日期月份分组以及对特定事件类型(如join/exit)进行计数统计。通过构建自定义分组键和链式stream操作,实现从原始数据结构到结构化统计结果的转换,并提供完整的代码示例和关键步骤解析。
在日常开发中,我们经常需要对数据进行复杂的聚合操作,例如从一组人员事件记录中,统计每个月不同事件类型(如“入职”或“离职”)的总人数。本教程将以一个具体的Java场景为例,演示如何使用Java 8 Stream API实现这一目标。
假设我们有以下人员(Person)事件数据:
import java.time.LocalDate;
// 定义事件类型枚举
public enum State {
JOIN, // 入职
EXIT // 离职
}
// Person类,存储人员事件信息
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, State event, LocalDate eventDate) {
this.id = id;
this.event = event;
this.eventDate = eventDate;
}
// Getters
public String getId() { return id; }
public State getEvent() { return event; }
public LocalDate getEventDate() { return eventDate; }
// 可根据需要添加其他方法
}我们的原始数据可能存储在一个Map<String, List<Person>>中,其中键是pId,值是该pId对应的Person事件列表。
最终我们希望得到如下形式的统计结果:
立即学习“Java免费学习笔记(深入)”;
Month Info Total Number 1 JOIN 2 1 EXIT 1 2 EXIT 1 3 JOIN 1
为了存储这个结果,我们定义一个数据传输对象(DTO):
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来作为这个复合键。使用record是更简洁的选择:
// Java 16+ 使用 record 作为分组键
public record MonthState(int month, State info) {}
// 对于Java 8-15,你需要一个普通的类,并重写 equals() 和 hashCode() 方法
/*
public class MonthState {
private int month;
private 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);
}
}
*/record会自动生成构造函数、equals()、hashCode()和toString()方法,非常适合作为不可变的数据载体。
现在,我们将逐步构建Stream管道来完成数据聚合:
首先,模拟一些原始数据:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamAggregationDemo {
public static void main(String[] args) {
// 模拟原始数据
Map<String, List<Person>> personListById = Map.of(
"per1", List.of(new Person("per1", State.JOIN, LocalDate.of(2022, 1, 10))),
"per2", List.of(new Person("per2", State.JOIN, LocalDate.of(2022, 1, 10))),
"per3", List.of(
new Person("per3", State.EXIT, LocalDate.of(2022, 1, 10)),
new Person("per3", State.EXIT, LocalDate.of(2022, 2, 10))
),
"per4", List.of(new Person("per4", State.JOIN, LocalDate.of(2022, 3, 10)))
);
// ... Stream 管道将在这里构建
}
}由于原始数据是一个Map<String, List<Person>>,我们需要将Map的值(List<Person>)扁平化成一个单一的Person对象流。
personListById.values().stream() // 获取 Map 中所有 List<Person> 的 Stream
.flatMap(List::stream) // 将每个 List<Person> 扁平化为 Person 对象的 Stream接下来,我们只关心JOIN和EXIT这两种事件类型。
.filter(person -> person.getEvent() == State.EXIT || person.getEvent() == State.JOIN)
这是核心步骤,我们将使用Collectors.groupingBy()方法。它需要两个参数:
.collect(Collectors.groupingBy(
p -> new MonthState(p.getEventDate().getMonthValue(), p.getEvent()), // 分组键:月份和事件类型
Collectors.counting() // 对每个分组中的元素进行计数
))这一步将返回一个Map<MonthState, Long>,其中键是MonthState对象,值是该组合下的Person数量。
现在我们有了一个Map<MonthState, Long>,需要将其转换回我们定义的List<DTO>形式。
.entrySet().stream() // 将 Map 转换为 Stream<Map.Entry<MonthState, Long>> .map(e -> new DTO(e.getKey().month(), e.getKey().info(), (int) (long) e.getValue())) // 映射为 DTO
为了使结果更具可读性,我们可以按月份对DTO列表进行排序。
.sorted(Comparator.comparing(DTO::getMonth)) // 按月份排序
最后,将Stream中的所有DTO对象收集到一个List中。
.toList(); // 收集为 List<DTO> (Java 16+) 或 .collect(Collectors.toList()) (Java 8-15)
将上述所有步骤组合起来,得到完整的Stream管道:
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
// 定义事件类型枚举
enum State {
JOIN, // 入职
EXIT // 离职
}
// Person类,存储人员事件信息
class Person {
private String id;
private State event; // 事件类型:JOIN 或 EXIT
private LocalDate eventDate; // 事件日期
public Person(String id, State event, LocalDate eventDate) {
this.id = id;
this.event = event;
this.eventDate = eventDate;
}
public String getId() { return id; }
public State getEvent() { return event; }
public LocalDate getEventDate() { return eventDate; }
}
// 分组键
record MonthState(int month, State info) {}
// 结果DTO
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;
}
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 +
'}';
}
}
public class StreamAggregationDemo {
public static void main(String[] args) {
// 模拟原始数据
Map<String, List<Person>> personListById = Map.of(
"per1", List.of(new Person("per1", State.JOIN, LocalDate.of(2022, 1, 10))),
"per2", List.of(new Person("per2", State.JOIN, LocalDate.of(2022, 1, 10))),
"per3", List.of(
new Person("per3", State.EXIT, LocalDate.of(2022, 1, 10)),
new Person("per3", State.EXIT, LocalDate.of(2022, 2, 10))
),
"per4", List.of(new Person("per4", State.JOIN, LocalDate.of(2022, 3, 10)))
);
List<DTO> result = personListById.values().stream()
.flatMap(List::stream) // 扁平化 List<Person>
.filter(person -> person.getEvent() == State.EXIT || person.getEvent() == State.JOIN) // 过滤事件类型
.collect(Collectors.groupingBy(
p -> new MonthState(p.getEventDate().getMonthValue(), p.getEvent()), // 按月份和事件类型分组
Collectors.counting() // 统计每个分组的数量
))
.entrySet().stream() // 将 Map 转换为 Stream<Map.Entry>
.map(e -> new DTO(e.getKey().month(), e.getKey().info(), (int) (long) e.getValue())) // 映射为 DTO
.sorted(Comparator.comparing(DTO::getMonth)) // 按月份排序
.toList(); // 收集结果 (Java 16+ 的简写,Java 8-15 使用 .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 8 Stream API进行多条件过滤、按复合键分组以及进行计数统计,从而高效地处理复杂的数据聚合任务。
以上就是Java 8 Streams:实现多条件过滤、按月分组及计数统计的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号