In your second code version:
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
The map Map<> seen
is initialized for every element x
, therefore your filter always return true
which will let all elements passthrough.
Move the Map<> seen
declaration to outside the lambda will correct your usage.
In the first code version, the Map<> seen
is only initialized one. What it returns is just a predicate:
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
When you pass this predicate to your stream, it does not create a new Map
but uses the reference Map<> seen
declared before.
1
solved why this lambda expression do not work when in statement ,but work in method?