【问题标题】:Remove duplicate entries from a list and keep last updated entry LocalDate从列表中删除重复条目并保留最后更新的条目 LocalDate
【发布时间】: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


【解决方案1】:

这个问题的另一种方法是使用groupingBycollector,然后使用collectingAndThencollector 找到最新的updatedDate。 我认为这种方式更具可读性和简洁性。

为了简化我将收集器导入为静态。

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.groupingBy;

Collection<Employee> collection = employees.stream()
         .collect(groupingBy(Employee::getId,
             collectingAndThen(maxBy(Comparator.comparing(Employee::getUpdatedDate)),
                            employee -> employee.orElse(null)))).values();

然后

List<Employee> result = new ArrayList<>(collection);

【讨论】:

    【解决方案2】:

    接受的答案可以进一步简化为

     Collection<Employee> collection = employees.stream()
        .collect(Collectors.toMap(Employee:: getId, Function.identity(),
            BinaryOperator.maxBy(Comparator.comparing(Employee:: getUpdatedDate)))).values();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多