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:
closureviaseeneven though the map itself is now out of scope.keyExtractorwill retrieve the key (either name or price) in your example via the setters provided as method references (e.g. XYZ::getName)putIfAbsenttries to add the boolean valuetrueto the map for the supplied key (in this case, thenameandpricefrom thekeyExtractor). If the key was already present, it returns that value which would betrue. Sincetrueis not equal tonull,falseis returned and the filter doesn't pass the value. If the value was not there, null is returned. Sincenull == nullis true,truewill 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
Bwas allowed thru the filter, the others were blocked.