public List<XYZ> getFilteredList(List<XYZ> l1) {
return l1
.stream()
.filter(distinctByKey(XYZ::getName))
.filter(distinctByKey(XYZ::getPrice))
.collect(Collectors.toList());
}
private 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;
}
Can anyone please help me,
What is the meaning of this line ------->
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
Why is the lambda result compared to null?
Your question revolves about the following:
closure
viaseen
even though the map itself is now out of scope.keyExtractor
will retrieve the key (either name or price) in your example via the setters provided as method references (e.g. XYZ::getName
)putIfAbsent
tries to add the boolean valuetrue
to the map for the supplied key (in this case, thename
andprice
from thekeyExtractor
). If the key was already present, it returns that value which would betrue
. Sincetrue
is not equal tonull
,false
is returned and the filter doesn't pass the value. If the value was not there, null is returned. Sincenull == null
is true,true
will be returned and the value passed thru the filter (i.e. it is thusfar distinct).Here is an example of how this would work. This uses a simple record and only applying a filter on name.
prints
Notice that only the first Name of
B
was allowed thru the filter, the others were blocked.