tags:

views:

106

answers:

5

Say I have a map of key -> value pairs, I want to reverse this so that I have a new map which is effectively value -> key (i.e. the old value becomes the new key and the old key becomes the new value).

Whats the best way to do this? (I am using Java...).

Oh and values are unique.

+2  A: 

Iterate over the entrySet:

for ( Map.Entry<K, V> entry : map.entrySet() ) {
    newMap.put(entry.getValue(), entry.getKey());
}
return newMap;
Mark Peters
+8  A: 

Personally I'd use a Guava BiMap to start with (with an implementation such as HashBiMap) and then call inverse() when I wanted to use the values as keys :)

Jon Skeet
Me too, +1. ...
Mark Peters
thats pretty cool
aeq
+1  A: 
Map<Type1,Type2> oldmap = getOldMap();
Map<Type2,Type1> newmap = new HashMap<Type2,Type1>();
for(Entry<Type1,Type2> entry : oldmap.entrySet()) {
    newmap.put(entry.getValue(),entry.getKey();
}
glowcoder
A: 

You may use any class that implements the "BidiMap" interface in the common collection from Apache (http://commons.apache.org/collections/). This is more efficient because the bidirectional map is constructed when you filled and there is no need to create a new map, which may not be practical when the map is big.

BidiMap aMap = new DualHashBidiMap();
aMap.put("B", "A");
aMap.put("A", "B");
aMap.put("C", "D");
aMap.put("X", "D");
MapIterator it = aMap.mapIterator();
System.out.println("Before Inverse");
while (it.hasNext()) {
    key = it.next();
    value = it.getValue();
    out.println(key + " -> " + value);
}
aMap = aMap.inverseBidiMap();
System.out.println("After Inverse");
it = aMap.mapIterator();
while (it.hasNext()) {
    key = it.next();
    value = it.getValue();
    out.println(key + " -> " + value);
}

Before Inverse
A -> B
B -> A
X -> D
After Inverse
D -> X
A -> B
B -> A
Ither
+1  A: 

I think there are enough solutions for your problem here. I just want to point out to be careful, because that may cause data loss if the values are not unique. F.e. if you have the following map:

A->X
B->Y
C->Y

and inverse it you will have either

X->A
Y->B

or

X->A
Y->C

which depends on the order of the insertions. By inversing it again, you will have one < key , value > pair less.

George B.
+1 for being the only one pointing out the danger.
Willi