Java – Generic keying across maps: Map from Map and Map

collectionsgenericsjavamaps

I have a function which returns a one-sided intersection of values between two input maps:

Map<Key, Value> mergeMaps(Map aKeys<CompositeKey, Key>, 
         Map <CompositeKey, Value> aValues) {

    Map<Key, Value> myResult = Maps.newHashMap();
    for (CompositeKey myKey : aKeys.keySet()) {
        if (aValues.containsKey(myKey)) {
            myResult.put( aKeys.get(myKey), aValues.get(myKey));
        }
    }
    return myResult;
}

This is not a transitive mapping composition i.e.

T->K, K->V ===> T->V

but instead transforming

T->(K,V) ===> K->V

Is there a way in Java to make this function generic such that its signature is as follows?

Map<K, V> mergeMaps(Map aKeys<T, K>, Map <T, V> aValues)

Best Answer

I think this signature should do what you want:

<T, K, V> Map<K, V> mergeMaps(Map<T, K> aKeys, Map<T, V> aValues)