假设我有一个键值对的映射表,我希望将其反转,得到一个新的映射表,这个新映射表的键值对是原映射表的值和键互换(即原来的值成为新映射表的键,原来的键成为新映射表的值)。
最好的方法是什么?(我在使用Java...)
哦,值都是唯一的。
遍历 entrySet
:
for ( Map.Entry<K, V> entry : map.entrySet() ) {
newMap.put(entry.getValue(), entry.getKey());
}
return newMap;
我认为你的问题已经有足够的解决方案了。我只想指出要小心,因为如果值不唯一,可能会导致数据丢失。
例如,如果你有下面这个映射:
A->X
B->Y
C->Y
X->A
Y->B
或者
X->A
Y->C
这取决于插入顺序。通过再次反转它,你会少一个 < key , value > 对。
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();
}
您可以使用实现了 Apache 公共集合中“BidiMap”接口的任何类(http://commons.apache.org/collections/)。这样更加高效,因为双向映射在填充时就已经构建好了,无需创建新的映射表,这在映射表很大时可能不切实际。
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