将集合里面的对象进行去重,超好用的方法!

加入一个静态方法,然后再需要的地方调用就好啦

 public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        //putIfAbsent方法添加键值对,如果map集合中没有该key对应的值,则直接添加,并返回null,如果已经存在对应的值,则依旧为原来的值。
        //如果返回null表示添加数据成功(不重复),不重复(null==null :TRUE)
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

调用示例:

  List<DghyYjhcHcxShare> bmShares = getShares(share);
//根据图层id去重
        bmShares = bmShares.stream().filter(distinctByKey(DghyYjhcHcxShare::getTcId)).collect(Collectors.toList());
有多种方法可以实现List集合根据对象属性,以下是其中几种常用的方法: 1. 对象的equals和hashCode方法 对象的equals和hashCode方法,根据属性判断两个对象是否相等,然后将对象放入Set集合。示例代码如下: ```java public class Person { private String name; private int age; // 省略构造方法和getter/setter方法 @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } } List<Person> personList = new ArrayList<>(); personList.add(new Person("张三", 20)); personList.add(new Person("李四", 22)); personList.add(new Person("张三", 20)); Set<Person> personSet = new HashSet<>(personList); System.out.println(personSet); ``` 输出结果为:`[Person{name='张三', age=20}, Person{name='李四', age=22}]` 2. 使用Java 8的stream和distinct方法 使用Java 8的stream和distinct方法,根据属性。示例代码如下: ```java List<Person> personList = new ArrayList<>(); personList.add(new Person("张三", 20)); personList.add(new Person("李四", 22)); personList.add(new Person("张三", 20)); List<Person> distinctPersonList = personList.stream().distinct().collect(Collectors.toList()); System.out.println(distinctPersonList); ``` 输出结果为:`[Person{name='张三', age=20}, Person{name='李四', age=22}]` 3. 使用Java 8的stream和toMap方法 使用Java 8的stream和toMap方法,根据属性。示例代码如下: ```java List<Person> personList = new ArrayList<>(); personList.add(new Person("张三", 20)); personList.add(new Person("李四", 22)); personList.add(new Person("张三", 20)); List<Person> distinctPersonList = personList.stream().collect(Collectors.toMap( person -> person.getName() + "-" + person.getAge(), person -> person, (oldValue, newValue) -> oldValue)).values().stream().collect(Collectors.toList()); System.out.println(distinctPersonList); ``` 输出结果为:`[Person{name='张三', age=20}, Person{name='李四', age=22}]` 以上是几种常用的List集合根据对象属性方法,可以根据实际场景选择合适的方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值