
场景概述
在数据处理中,我们经常会遇到需要从一个对象列表中移除重复项的情况。一个常见的需求是:当多个对象拥有相同的唯一标识(如ID)时,我们希望保留其中某个特定条件的对象,例如拥有最新时间戳(或最大/最小数值)的记录。本教程将以一个具体的示例来演示如何使用Java Stream API高效、简洁地实现这一目标。
假设我们有一个Student对象列表,每个Student对象包含一个id和一个startDatetime。如果列表中存在多个Student对象具有相同的id,我们希望只保留其中startDatetime最新的那个对象。
核心解决方案:Collectors.toMap与合并函数
Java Stream API提供了一个强大的工具——Collectors.toMap,它有多个重载版本。为了解决我们的问题,我们将使用其三参数版本: Collectors.toMap(keyMapper, valueMapper, mergeFunction)
- keyMapper: 用于从流中的每个元素提取Map的键。在本例中,即Student::getId。
- valueMapper: 用于从流中的每个元素提取Map的值。由于我们想保留整个Student对象作为值,可以使用Function.identity()。
- 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 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 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"的学生由于唯一,被直接保留。
注意事项
-
mergeFunction的选择:
- 如果需要保留最旧的记录,应使用BinaryOperator.minBy(Comparator.comparing(Student::getStartDatetime))。
- 如果需要根据其他属性(如数字大小)进行筛选,只需修改Comparator.comparing()的参数即可。
- 结果集的顺序: Collectors.toMap在内部使用HashMap(默认情况下),因此其结果Map的values()集合的顺序是不确定的。如果最终的List需要保持特定的顺序(例如按ID排序或按时间排序),则需要像示例中那样在values().stream()之后显式地添加.sorted()操作。
- 内存消耗: toMap操作会创建一个中间的Map来存储去重后的元素。对于非常大的数据集,这可能会占用较多的内存。但在大多数常见场景下,这种方法是高效且可接受的。
- Java版本兼容性: 在Java 16及更高版本中,可以使用.toList()作为终端操作来收集Stream元素到不可变列表。对于早期版本(如Java 8),应使用Collectors.toList()。
- Function.identity(): 这个静态方法返回一个函数,该函数总是返回其输入参数。在这里,它确保Map的值就是流中当前的Student对象本身。
总结
通过本教程,我们学习了如何巧妙地运用Java Stream API中的Collectors.toMap结合BinaryOperator.maxBy(或minBy)来解决列表去重并保留特定条件记录的问题。这种方法不仅代码简洁、可读性强,而且在处理集合数据时表现出良好的性能。掌握这种模式对于编写高效且富有表现力的Java代码至关重要。










