How to use lambda/Stream api to filter distinct elements by object Attribute/Property

Viewed 1112

I have a List of Object. Every object has a map with a key named "xyz". I want elements in the list which has unique value to that particular key.

I know we can do this easily with set/map but I'm particularly looking for lambda solution.

I thought this would work.

list.stream()
    .filter(distinctByXyz(f -> f.getMap.get("xyz")))
    .collect(Collectors.toList()));

I've a function to distinct them

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

The problem is the function f.getMap() inside filter isnt working. Showing compilation error (Cannot resolve method)

1 Answers
Related