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

版权声明:本文为IT_Octopus原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。