Harshit Gupta
Harshit Gupta

Reputation: 335

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

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)

Upvotes: 3

Views: 1203

Answers (1)

Eugene
Eugene

Reputation: 120848

You seem to have a few typos in your code, this should work:

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

You are using distinctByXyz when it should really be distinctByKey. Then f.getMap that should probably be f.getMap() and also you are slightly off with your parenthesis.

Upvotes: 4

Related Questions