问题
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.
回答1:
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 :)
回答2:
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.
回答3:
Iterate over the entrySet:
for ( Map.Entry<K, V> entry : map.entrySet() ) {
newMap.put(entry.getValue(), entry.getKey());
}
return newMap;
回答4:
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();
}
回答5:
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
来源:https://stackoverflow.com/questions/3347570/transpose-a-hashmap-for-key-value-to-value-key