Daily Code - JAVA去重

221 阅读1分钟

通过Map的Key不能相同来去重

private 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;
    }

使用方式

 List<Item> noRepeat = repeats.stream().filter(distinctByKey(i -> i.getId())).collect(Collectors.toList());

A9DC4EB6976C8B229F157AE5D960A460.gif