user1424934
user1424934

Reputation: 153

Google Guava Function for extracting a key from Map.Entry

I would like to have a something like this (Java):

class MapEntries {

    private static final Function<Map.Entry<Object, Object>, Object> EXTRACT_KEY =
        new Function<Map.Entry<Object, Object>, Object>() {
          @Override
          public Object apply(Map.Entry<Object, Object> input) {
              return input.getKey();
          }
    }

    public static <K, V> Function<Map.Entry<K, V>, K> extractKey() {
        return EXTRACT_KEY;
    }
}

Note that EXTRACT_KEY is a singleton, and extractKey() uses generics for type safety.

Unfortunately, javac complains about illegal cast when I write return EXTRACT_KEY;. I tried many variants but nothing seems to work. There must be a way to do this. Anyone?

edit:

I forgot to mention that somewhere else in the code I would like to do:

void foo(Iterable<? extends Entry<K, V>> entries) {                
    Iterable<T> keys = Iterables.<Entry<K, V>, K>transform(entries,
                             MapEntries.extractKey());
    // more code follows...
}

Using the (Function) EXTRACT_KEY cast solved the compilation error in MapEntries. However javac still complains about foo():

The parameterized method <Map.Entry<K,V>, T>transform(Iterable<Map.Entry<K,V>>, Function<? super Map.Entry<K,V>,? extends K>) of type Iterables is not applicable for the arguments (Iterable<capture#13-of ? extends Map.Entry<K,V>>,Function,Object>)

Upvotes: 0

Views: 351

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198123

You must either stop treating EXTRACT_KEY as a singleton -- allocating a new Function each time -- or accept the need for an unsafe cast, which can by done with return (Function) EXTRACT_KEY.

Upvotes: 2

Related Questions