Pair values from two maps based on same key

Given the following two maps with values of different types but same key types

Map<Key, Dog> indexedDogs =  Maps.uniqueIndex(dogs, keyGeneratorForDog);
Map<Key, Cat> indexedCats=  Maps.uniqueIndex(cats, keyGeneratorForCat);

I would like to pair values together based on same key:

Map<Dog, Cat> pairs = pair(indexedDogs, indexedCats);

Is there implementation for pair() method in Guava or something that can be easily built on top of existing Guava methods?

Answer

You can write your own method, which wouldn’t be that difficult. First you need to get the Set intersection of the keys in those maps. Youc an use Set#retainAll() method for that.

Then iterate over the set, and add values from both map into the new map for each key, someway along the lines of:

public Map<Dog, Cat> pair(Map<Key, Dog> indexedDogs, Map<Key, Cat> indexedCats) {
    Set<Key> commonKey = indexedDogs.keySet();
    commonKey.retainAll(indexedCats.keySet());

    Map<Dog, Cat> map = new HashMap<>();

    for (Key key: commonKey) {
        map.put(indexedDogs.get(key), indexedCats.get(key));
    }

    return map; 
}

Leave a Reply

Your email address will not be published. Required fields are marked *