I'm stuck on how to transfer key-value pairs from map1 into map2 only if each key has a unique value in map1.
Let's say I have the following maps:
- map1: [1,2] [2,4] [4,4]
- map2: [1,2] [2,4]
I suppose the algorithm would be:
- Loop through entries in the first map.
- Add a key to map2.
- Add a value to a set which checks against the values of map2
- If the values are duplicate the value doesn't get added to the set and disregard adding its corresponding key to map2.
Code snippet:
public static <K,V> Map<K,V> unique (Map<K,V> m) {
Map<K,V> newMap = new ArrayMap<K,V>();
//Remember all values in the newMap.
Set<V> holding = new ArraySet<V>(newMap.values());
for (Map.Entry<K, V> graphEntry : m.entries()) {
//not sure.
}
return newMap;
}
Is my idea of how its supposed to be done on the right track? Quite lost here.
{1:2,4:4}
? Why do you choose2
? Does it not matter? - cheeken