jdk8 stream 根據屬性去重

Im灬大神發表於2020-12-10

private void book(List<Item> books){

      List<Integer> bookIds = books.stream().filter(distinctByKey(m ->m.getBookId())).map(m -> m.getBookId()).collect(Collectors.toList());
 
	}


    
//根據屬性去重 distinct
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;
    }

相關文章