java 对象集合排序再排序后顺序去重(只取最前面的唯一)

    /**
     * 按照①endTime正序②startTime倒序  进行排序
     * @param effectiveCoupon
     * @return
     */
    private List<CouponStatusInfo> listSort(List<CouponStatusInfo> effectiveCoupon) {
        List<CouponStatusInfo> newList = effectiveCoupon.stream().sorted(Comparator
                .comparing(CouponStatusInfo::getEndTime)
                .thenComparing(CouponStatusInfo::getStartTime, Comparator.reverseOrder())
        ).filter(distinctByKey(item->item.getActivityId())).collect(Collectors.toList());
        log.debug("---listSort.newList: {}", newList);
        return newList;
    }

    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

第二种写法

        List<CouponStatusInfo> newList = items.stream().sorted(Comparator
                        .comparingLong(CouponStatusInfo::getEndTime)
                        .thenComparing(CouponStatusInfo::getStartTime,Comparator.reverseOrder())
        ).filter(distinctByKey(item->item.getActivityId())).collect(Collectors.toList());
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

下面的代码可以理解为:

        Map<Object,Boolean> seen111 = new ConcurrentHashMap<>();
        List<CouponStatusInfo> newList = items.stream().sorted(Comparator
                        .comparingLong(CouponStatusInfo::getEndTime)
                        .thenComparing(CouponStatusInfo::getStartTime,Comparator.reverseOrder())
        ).filter(t -> seen111.putIfAbsent(t.getActivityId(), Boolean.TRUE) == null).collect(Collectors.toList());
Map api
// 如果所指定的 key 已经在 HashMap 中存在,返回和这个 key 值对应的 value, 如果所指定的 key 不在 HashMap 中存在,则返回 null。
putIfAbsent
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值