Draco Malfoy
Draco Malfoy

Reputation: 11

Using lambda expression to access a value in a map using an optional key

I need to access a value from a map M<X,Y> and I have a key of type Optional<X> key. I need to use lambda expression such that I can check whether the key is present, if present, access the value using it otherwise, return empty.

I am doing:

return key.ifPresent(xx -> {
    Optional.of(M.getOrDefault(foo(xx), null));
});

But it is giving void type provided but required type is Optional. Suggestions into this?

Upvotes: 0

Views: 965

Answers (1)

Naman
Naman

Reputation: 31878

you could b looking for something like:

private Optional<Y> findingY( Map<X,Y> M, Optional<X> key) {
    return key.map(M::get);
}

Upvotes: 1

Related Questions