How Predicate maintains state in Java 8

I review this code and try to understand the following code snippet.

copied from Stuart Marks answer

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

BigDecimal totalShare = orders.stream()
    .filter(distinctByKey(o -> o.getCompany().getId()))
    .map(Order::getShare)
    .reduce(BigDecimal.ZERO, BigDecimal::add);

My question here every time distinctByKey will be called and as a result a new ConcurrentHashMap will be created . how it maintains state using the new ConcurrentHashMap <> (); ?

+4
source share
3 answers

Since this is an exciting lambda, indeed, a new instance Predicatewill return all the time for every call, but these instances will have the same ConcurrentHashMapand Function.

Btw a System.out.println distinctByKey - , .

Djdk.internal.lambda.dumpProxyClasses=/Your/Path/Here

, < > Predicate class. - CHM Function, private static factory method, . , , Predicate, ConcurrentHashMap Function.

+4

, . , distinctByKey , ConcurrentHashMap -. , distinctByKey Predicate, .

+4

" distinctByKey ConcurrentHashMap. , ConcurrentHashMap < > ();?"

, distinctByKey . , distinctByKey sysout .

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

distinctByKey , , . .

enter image description here

+3

Source: https://habr.com/ru/post/1689550/


All Articles