java集合去重_如何对 Java 中的集合进行去重

整体去重

如果是普通的去重,就用最常见的 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()));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值