AbNig
AbNig

Reputation: 352

Lambda expression to search a Java Map using value

I have to implement the following method which takes in a value element in a Java Map and returns a Set of pojo encapsulating key & value objects in the Map.

public Set<CacheElement<K, V>> searchByValue(V v);

The CacheElement class is as follows:

public final class CacheElement<K, V> {

    private final K k;
    private final V v;

    public CacheElement(K k, V v) {
        super();
        this.k = k;
        this.v = v;
    }

    public K getK() {
        return k;
    }

    public V getV() {
        return v;
    }   
}

I have written the following method to find the Set of key elements in the Map corresponding to the value passed.

public Set<CacheElement<K, V>> searchByValue(V v) {

    Set<K> keySet = this.cacheMap.entrySet().stream()
    .filter(entry -> entry.getValue().equals(v))
    .map(entry -> entry.getKey())
    .collect(Collectors.toSet());

    return null;
}

I am not sure how to write lambda to pass the keySet to the Map and get back a Set containing matched CacheElement<K,V>.

I have written the following incomplete labmda:

    Set<CacheElement<K, V>> elements = this.cacheMap.entrySet().stream()
    .filter(entry ->keySet.contains(entry.getKey()))
    .map(entry -> new CacheElement<K, V>(entry.getKey(), entry.getValue()));

I need help in collecting the newly created CacheElement object in a set.

The code is available at: https://github.com/abnig/ancache

Thanks

Edit-1:

The cacheMap is

private Map<K, V> cacheMap = new ConcurrentHashMap<K, V>();

When I added the .collect operand

Set<CacheElement<K, V>> elements = cacheMap.entrySet().stream()
.filter(entry ->keySet.contains(entry.getKey()))
.map(entry -> new CacheElement<K, V>(entry.getKey(), entry.getValue())
.collect(Collectors.toSet()));

Then I get the following errors:

Type mismatch: cannot convert from Stream<Object> to Set<CacheElement<K,V>> line 92 Java Problem 

The method collect(Collectors.toSet()) is undefined for the type CacheElement<K,V>  line 95 Java Problem

Line #92 is: Set<CacheElement<K, V>> elements = cacheMap.entrySet().stream()

Line #95 is: collect(Collectors.toSet()))

Edit-2

enter image description here

Upvotes: 2

Views: 2832

Answers (1)

Naman
Naman

Reputation: 31878

You're primarily missing the collect (toSet) and returning the result. You can also make sure to do the complete operation combining that logic with collect and return as:

public Set<CacheElement<K, V>> searchByValue(V v) {
    return this.cacheMap.entrySet().stream() // assuming Map<K, V> cacheMap
            .filter(entry -> entry.getValue().equals(v)) // filter entries with same value 'v'
            .map(entry -> new CacheElement<>(entry.getKey(), entry.getValue())) // map key and value to CacheElement
            .collect(Collectors.toSet()); // collect as a Set
}

Upvotes: 2

Related Questions