
在数据处理中,我们经常会遇到需要从一个对象列表中移除重复项的情况。一个常见的需求是:当多个对象拥有相同的唯一标识(如ID)时,我们希望保留其中某个特定条件的对象,例如拥有最新时间戳(或最大/最小数值)的记录。本教程将以一个具体的示例来演示如何使用Java Stream API高效、简洁地实现这一目标。
假设我们有一个Student对象列表,每个Student对象包含一个id和一个startDatetime。如果列表中存在多个Student对象具有相同的id,我们希望只保留其中startDatetime最新的那个对象。
Java Stream API提供了一个强大的工具——Collectors.toMap,它有多个重载版本。为了解决我们的问题,我们将使用其三参数版本: Collectors.toMap(keyMapper, valueMapper, mergeFunction)
为了保留具有最新startDatetime的Student对象,我们需要一个合并函数,它能在两个Student对象中选择startDatetime更大的那个。BinaryOperator.maxBy()正好可以满足这个需求,它接收一个Comparator作为参数,并返回一个BinaryOperator,该操作符会根据Comparator选择两个输入中“更大”的一个。
结合Comparator.comparing(Student::getStartDatetime),我们可以构建出BinaryOperator.maxBy(Comparator.comparing(Student::getStartDatetime))作为合并函数。这意味着,当遇到相同的id时,toMap会比较两个Student对象的startDatetime,并保留时间较晚(即更大)的那个。
立即学习“Java免费学习笔记(深入)”;
首先,定义我们的Student类:
import java.time.LocalDateTime;
import java.util.Objects;
public class Student {
private String id;
private LocalDateTime startDatetime;
public Student(String id, LocalDateTime startDatetime) {
this.id = id;
this.startDatetime = startDatetime;
}
public String getId() {
return id;
}
public LocalDateTime getStartDatetime() {
return startDatetime;
}
// 建议重写toString()方法,便于调试
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", startDatetime=" + startDatetime +
'}';
}
// 建议重写equals()和hashCode(),如果Student对象需要作为Set元素或Map的键
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(id, student.id) && Objects.equals(startDatetime, student.startDatetime);
}
@Override
public int hashCode() {
return Objects.hash(id, startDatetime);
}
}接下来,是去重并保留最新记录的核心逻辑:
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
public class StudentDeduplicator {
public static void main(String[] args) {
// 示例数据
List<Student> students = List.of(
new Student("1", LocalDateTime.of(2022, 11, 1, 14, 0)), // 最新
new Student("1", LocalDateTime.of(2000, 2, 1, 1, 1)), // 较旧
new Student("1", LocalDateTime.of(1990, 2, 1, 1, 1)), // 最旧
new Student("2", LocalDateTime.of(1990, 2, 1, 1, 1)), // 唯一
new Student("3", LocalDateTime.of(2023, 1, 1, 10, 0)), // 最新
new Student("3", LocalDateTime.of(2022, 1, 1, 10, 0)) // 较旧
);
System.out.println("原始学生列表:");
students.forEach(System.out::println);
// 使用Stream API去重并保留最新记录
List<Student> uniqueStudents = students.stream()
.collect(Collectors.toMap(
Student::getId, // keyMapper: 以ID作为Map的键
Function.identity(), // valueMapper: 整个Student对象作为Map的值
BinaryOperator.maxBy(Comparator.comparing(Student::getStartDatetime)) // mergeFunction: 当ID重复时,保留startDatetime更大的那个
))
.values() // 获取Map中所有去重后的Student对象
.stream() // 转换为新的Stream
.sorted(Comparator.comparing(Student::getId)) // 可选:按ID排序,使结果有序
.collect(Collectors.toList()); // 收集为List (Java 16+ 可用 .toList())
System.out.println("\n去重并保留最新记录后的学生列表:");
uniqueStudents.forEach(System.out::println);
}
}输出结果:
原始学生列表:
Student{id='1', startDatetime=2022-11-01T14:00}
Student{id='1', startDatetime=2000-02-01T01:01}
Student{id='1', startDatetime=1990-02-01T01:01}
Student{id='2', startDatetime=1990-02-01T01:01}
Student{id='3', startDatetime=2023-01-01T10:00}
Student{id='3', startDatetime=2022-01-01T10:00}
去重并保留最新记录后的学生列表:
Student{id='1', startDatetime=2022-11-01T14:00}
Student{id='2', startDatetime=1990-02-01T01:01}
Student{id='3', startDatetime=2023-01-01T10:00}从输出可以看出,对于ID为"1"的三个学生,只保留了startDatetime为2022-11-01T14:00的那个。对于ID为"3"的两个学生,保留了startDatetime为2023-01-01T10:00的那个。ID为"2"的学生由于唯一,被直接保留。
通过本教程,我们学习了如何巧妙地运用Java Stream API中的Collectors.toMap结合BinaryOperator.maxBy(或minBy)来解决列表去重并保留特定条件记录的问题。这种方法不仅代码简洁、可读性强,而且在处理集合数据时表现出良好的性能。掌握这种模式对于编写高效且富有表现力的Java代码至关重要。
以上就是使用Java Stream高效处理列表重复对象:按ID去重并保留最新记录的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号