Kevin Meredith
Kevin Meredith

Reputation: 41909

Generic Method to Get Optional Item from Map

In Java 8, I'm trying to define a generic method to look up whether a Map<K, V> contains a K key:

private static Optional<V> find(final Map<K, V> map, final K key) {
    final V result = map.get(key);
    return (result == null) ? Optional.empty() : Optional.of(key);
}

But I get a bunch of compile-time errors on K and V:

[ERROR] ... Compilation failure:
[ERROR] ~/App.java:[31,47] cannot find symbol
[ERROR] symbol:   class K
[ERROR] location: class com.myapp.app.App
[ERROR] ~/App.java:[31,50] cannot find symbol
[ERROR] symbol:   class V
[ERROR] location: class com.myapp.app.App

How can I resolve these errors?

Upvotes: 0

Views: 1025

Answers (1)

Kevin Meredith
Kevin Meredith

Reputation: 41909

private static <K, V> Optional<V> find(final Map<K, V> map, final K key) {
    final V result = map.get(key);
    return Optional.ofNullable(result);
}

Credit - Sotirios Delimanolis for mentioning Option#ofNullable and my failure to list generic parameters.

Upvotes: 1

Related Questions