JAVA8 lambda按指定字段去重

childList = childList.stream().collect(
        Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.get("id").toString()))), ArrayList::new))

使用到了collectingAndThen完成根据属性进行去重的操作,对于该去重操作的关键使用到了collectingAndThen、toCollection、TreeSet,有点难以理解。

//构造一个基于id比较器的treeSet
TreeSet<HashMap<String,Object>> treeSet = new TreeSet<>(Comparator.comparing(o->o.getString("id")));

//将元素塞进treeSet
for (HashMap map : childList){
    treeSet.add(map);
}
//转换成List
List<HashMap<String,Object>> result2 =  new ArrayList<>(treeSet);

理解根据对象的属性进行去重的核心是,将集合放到TreeSet中,然后再将TreeSet转为List, 其中TreeSet要传入一个根据哪个属性进行比较的比较器,然后使用public ArrayList(Collection<? extends E> c)将TreeSet放入构造器中生成List。

collectingAndThen:进行结果的收集 ,再进行下一步的处理。

   public static<T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream,
                                                                Function<R,RR> finisher) {
参数1:stream 流 Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.get("id").toString())))

参数2;ArrayList的有参构造方法: ArrayList::new

最后收集流到List 集合当中:childList.stream().collect

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值