从列表中删除重复的条目,并保留最后更新的条目LocalDate

戈文达·萨哈雷(Govinda Sakhare):

我有一个具有以下字段的员工班。

class Employee {
    final int id;
    final String name;
    final LocalDate updatedDate;
    // setters and getters
}

我有一个雇员列表,该列表可以包含具有不同的重复雇员updatedDate现在,我要创建一个集合,使每个集合都有一个唯一的条目employeeId如果有重复的条目,updatedDate则应保留最新的条目

我提出了以下解决方案,根据进行排序updatedDate并添加,TreeSet以保持的唯一性Id我可以HashSet通过在Employee中实现哈希码和等于来使用

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);

现在的问题是,大多数时候员工列表将包含唯一元素。很少有重复的条目。仅存在唯一条目时排序将无法很好地扩展。有没有一种方法可以通过避免排序来改善上述解决方案?

哈迪J:

解决此问题的另一种方法是使用groupingBy收集器,然后使用collectingAndThen收集器查找最新的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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章