【发布时间】:2020-07-08 09:49:31
【问题描述】:
我有一个包含以下字段的员工类。
class Employee {
final int id;
final String name;
final LocalDate updatedDate;
// setters and getters
}
我有一个员工列表,该列表可能包含具有不同 updatedDate 的重复员工。现在,我想创建一个集合,使每个employeeId 都有一个唯一的条目。如果有重复条目,则应保留具有最新updatedDate 的条目。
我想出了以下解决方案,根据updatedDate 排序并添加它TreeSet,它在Id 上保持唯一性。我可以通过在 Employee 中实现 hashcode & equals 来使用HashSet。
List<Employee> employees = new ArrayList<>();
// sort
List<Employee> sortedList = employees.stream()
.sorted(Collections.reverseOrder(Comparator.comparing(employee -> employee.updatedDate)))
.collect(Collectors.toList());
Set<Employee> employeeSet = new TreeSet<>(Comparator.comparing( employee -> employee.id));
sortedList.forEach(employeeSet::add);
现在的问题是,大多数时候员工列表都会包含独特的元素。很少有重复的条目。仅存在唯一条目时的排序将无法很好地扩展。有没有办法通过避免排序来改进上述解决方案?
【问题讨论】:
-
stream 有一个
distinct()函数,你应该检查一下......按员工 ID 排序,然后是时间戳 desc.. 然后调用 distinct() -
这仅在 .equals() 实现不包含更新日期时才有效
-
您没有在代码中使用
TreeMap,而是TreeSet。
标签: java algorithm java-8 distinct-values