java去重

157 阅读1分钟

整体去重

如果是普通的去重,就用最常见的 HashSet 就好:

Set employeeSet = new HashSet<>(employeeList);

employeeList.clear();

employeeList.addAll(employeeSet);

或者使用 Java8 的 Stream API:

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

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

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

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

方式 1:

List uniqueList = employeeList.stream().collect(

Collectors.collectingAndThen(

Collectors.toCollection(

() -> new TreeSet<>(Comparator.comparingLong(Employee::getId))

),

ArrayList::new

)

);

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

方式 2:

HashSet idSet = new HashSet<>();

employeeList.removeIf(employee -> !idSet.add(employee.getId()));