Java 集合去重

admin 阅读:439 2024-04-26

整体去重

如果是普通的去重,最常见的方法是使用 HashSet:

Set<Employee> employeeSet = new HashSet<>(employeeList);
employeeList.clear();
employeeList.addAll(employeeSet);

或者也可以使用 Stream API:

List<Employee> uniqueList = employeeList.stream().distinct().collect(Collectors.toList());

注:Employee 类需要实现 hashCode 及 equals 方法。

根据对象中的某个属性进行去重

例如:不重写 equals 方法的情况下,根据 Employee 的 id 字段进行去重处理

方式 1:

List<Employee> uniqueList = employeeList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparingLong(Employee::getId))
),
ArrayList::new
)
);

如果是依照两个字段进行去重,则重写 Comparator 方法即可。

方式 2:

HashSet<Object> idSet = new HashSet<>();
employeeList.removeIf(employee -> !idSet.add(employee.getId()));
声明

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!