java中的info属性_使用java8实现List中对象属性的去重

本文介绍了如何使用Java8的Stream流来优雅地实现List中对象属性的去重,避免了传统的双重for循环或者for+Map的方法。通过创建一个TreeSet并指定比较器进行排序和去重,然后利用collectingAndThen方法将结果转换为ArrayList。这种方法既简洁又高效,展示了Java8的新特性。
摘要由CSDN通过智能技术生成

使用java8实现List中对象属性的去重

今天在工作的时候遇到了一个问题,就是List的去重,不想用双重for,感觉太low,不想用for+Map,感觉应该有更好的方法,于是,google之。发现java8的stream流能完美解决这个问题。

List list

比如在 BookInfoVo 中有一个 recordId 属性,现在需要对此去重.

怎么办呢?

有两种方法:

第一种: 不使用java8

private List removeDupliByRecordId(List persons) {

Set personSet = new TreeSet<>((o1, o2) -> o1.getRecordId().compareTo(o2.getRecordId()));

personSet.addAll(persons);

return new ArrayList(personSet);

}

这也是大多数人第一想到的,借助 TreeSet 去重,其中 TreeSet 的其中一个构造函数接收一个排序的算法,同时这也会用到 TreeSet 的去重策略上.

/** * Constructs a new, empty tree set, sorted according to the specified * comparator. All elements inserted into the set must be mutually * comparable by the specified comparator: {@code comparator.compare(e1, * e2)} must not throw a {@code ClassCastException} for any elements * {@code e1} and {@code e2} in the set. If the user attempts to add * an element to the set that violates this constraint, the * {@code add} call will throw a {@code ClassCastException}. * * @param comparator the comparator that will be used to order this set. * If {@code null}, the {@linkplain Comparable natural * ordering} of the elements will be used. */

public TreeSet(Comparator super E> comparator) {

this(new TreeMap<>(comparator));

}

第二种: 炫酷的java8写法

/*方法二:炫酷的java8写法*/

ArrayList distinctLiost = list.stream()

.collect(

Collectors.collectingAndThen(

Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingLong(BookInfoVo::getRecordId))), ArrayList::new)

);

如果没有第一种方法做铺垫,我们很可能一脸懵逼.

其实理解起来也不难:

关键在于Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingLong(BookInfoVo::getRecordId))), ArrayList::new)的理解,

collectingAndThen 这个方法的意思是: 将收集的结果转换为另一种类型: collectingAndThen,

因此上面的方法可以理解为,把 new TreeSet<>(Comparator.comparingLong(BookInfoVo::getRecordId))这个set转换为 ArrayList,这个结合第一种方法不难理解.

可以看到java8这种写法真是炫酷又强大!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值