
本文详细介绍了如何利用java stream api高效处理复杂数据。通过一个具体案例,演示了如何结合多条件过滤、自定义分组键(按日期月份和事件类型)、以及使用`collectors.counting()`进行聚合计数,最终将处理结果转换为结构化的dto列表,帮助开发者掌握java 8+流式编程的高级技巧。
在现代Java应用开发中,数据处理是核心任务之一。Java 8引入的Stream API极大地简化了集合数据的操作,使其更具可读性和表达力。本文将深入探讨如何利用Stream API实现复杂的数据转换需求,包括多条件过滤、按日期字段(月份)分组,并对分组结果进行聚合计数。我们将通过一个具体的场景来演示这些高级特性。
假设我们有一个包含人员事件信息的列表。每个Person对象记录了一个事件(如JOIN入职或EXIT离职)及其发生的日期。我们的目标是统计每个月不同事件类型(JOIN或EXIT)的总人数。
首先,我们定义相关的数据模型:
Person 类:表示一个人员事件。
立即学习“Java免费学习笔记(深入)”;
import java.time.LocalDate;
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;
}
public String getId() { return id; }
public State getEvent() { return event; }
public LocalDate getEventDate() { return eventDate; }
// 假设 State 是一个枚举类型
public enum State {
JOIN, EXIT, OTHER
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", event=" + event +
", eventDate=" + eventDate +
'}';
}
}DTO 类:表示最终的统计结果。
public class DTO {
private int month;
private Person.State info;
private int totalEmployees;
public DTO(int month, Person.State info, int totalEmployees) {
this.month = month;
this.info = info;
this.totalEmployees = totalEmployees;
}
public int getMonth() { return month; }
public Person.State getInfo() { return info; }
public int getTotalEmployees() { return totalEmployees; }
@Override
public String toString() {
return "DTO{" +
"Month=" + month +
", Info=" + info +
", Total Number=" + totalEmployees +
'}';
}
}为了实现按月份和事件类型同时分组,我们需要一个复合键。Java 16及更高版本推荐使用record类型来简洁地定义这样的数据载体;对于早期版本,可以使用一个普通的class。
// Java 16+ 的 record
public record MonthState(int month, Person.State info) {}
// Java 8-15 的 class 等效实现
/*
public class MonthState {
private final int month;
private final Person.State info;
public MonthState(int month, Person.State info) {
this.month = month;
this.info = info;
}
public int getMonth() { return month; }
public Person.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);
}
}
*/注意:如果使用class,必须正确实现equals()和hashCode()方法,以确保Map能够正确地将具有相同月份和事件状态的对象视为相同的键。record类型会自动生成这些方法。
我们将从一个Map<String, List<Person>>类型的数据源开始,其中键是pId,值是该pId对应的Person对象列表。
import java.util.*;
import java.util.stream.Collectors;
import java.time.LocalDate;
public class StreamGroupingExample {
public static void main(String[] args) {
// 示例数据初始化
Map<String, List<Person>> personListById = new HashMap<>();
personListById.put("per1", Arrays.asList(
new Person("per1", "John", "Doe", Person.State.JOIN, LocalDate.of(2022, 1, 10))
));
personListById.put("per2", Arrays.asList(
new Person("per2", "Jane", "Smith", Person.State.JOIN, LocalDate.of(2022, 1, 10))
));
personListById.put("per3", Arrays.asList(
new Person("per3", "Bob", "Johnson", Person.State.EXIT, LocalDate.of(2022, 1, 10)),
new Person("per3", "Bob", "Johnson", Person.State.EXIT, LocalDate.of(2022, 2, 10))
));
personListById.put("per4", Arrays.asList(
new Person("per4", "Alice", "Williams", Person.State.JOIN, LocalDate.of(2022, 3, 10))
));
personListById.put("per5", Arrays.asList( // 包含其他事件类型的示例
new Person("per5", "Charlie", "Brown", Person.State.OTHER, LocalDate.of(2022, 1, 15))
));
// Stream 管道处理
List<DTO> result = personListById.values().stream()
// 1. 扁平化处理:将Map中所有List<Person>合并成一个Person流
.flatMap(List::stream)
// 2. 多条件过滤:只保留JOIN或EXIT事件类型的Person对象
.filter(per -> per.getEvent() == Person.State.EXIT || per.getEvent() == Person.State.JOIN)
// 3. 核心分组与计数:
// - 使用MonthState作为分组键,结合月份和事件类型
// - 使用Collectors.counting()作为下游收集器,计算每个分组中的元素数量
.collect(Collectors.groupingBy(
p -> new MonthState(p.getEventDate().getMonthValue(), p.getEvent()),
Collectors.counting() // 统计每个分组的元素数量
))
// 4. 将Map<MonthState, Long>的entrySet转换为Stream<Map.Entry<MonthState, Long>>
.entrySet().stream()
// 5. 映射为DTO对象:将Map.Entry转换为我们期望的DTO格式
.map(entry -> new DTO(entry.getKey().month(), entry.getKey().info(), entry.getValue().intValue()))
// 6. 排序:按月份升序排列
.sorted(Comparator.comparing(DTO::getMonth))
// 7. 收集结果:将Stream<DTO>收集为List<DTO>
.toList(); // Java 16+,等同于 .collect(Collectors.toList())
// 打印结果
result.forEach(System.out::println);
/* 预期输出:
DTO{Month=1, Info=JOIN, Total Number=2}
DTO{Month=1, Info=EXIT, Total Number=1}
DTO{Month=2, Info=EXIT, Total Number=1}
DTO{Month=3, Info=JOIN, Total Number=1}
*/
}
}personListById.values().stream():
.flatMap(List::stream):
.filter(per -> per.getEvent() == Person.State.EXIT || per.getEvent() == Person.State.JOIN):
.collect(Collectors.groupingBy(p -> new MonthState(p.getEventDate().getMonthValue(), p.getEvent()), Collectors.counting())):
.entrySet().stream():
.map(entry -> new DTO(entry.getKey().month(), entry.getKey().info(), entry.getValue().intValue())):
.sorted(Comparator.comparing(DTO::getMonth)):
.toList():
通过本文的详细讲解和示例,我们展示了如何利用Java Stream API的强大功能,结合多条件过滤、自定义分组键以及Collectors.groupingBy和counting()等高级特性,高效地处理复杂的数据聚合需求。掌握这些技巧将使您在日常开发中能够编写出更简洁、更具表达力且性能优越的数据处理代码。
以上就是Java Stream API实战:实现多条件过滤、按日期月份分组及聚合计数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号