简体   繁体   English

将key-> value的hashmap“转置”为value-> key?

[英]“Transpose” a hashmap for key->value to value->key?

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 (ie 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...). (我正在使用Java ......)。

Oh and values are unique. 哦,价值观是独一无二的。

就个人而言,我会使用Guava BiMap (使用HashBiMap等实现),然后在我想将值用作键时调用inverse() :)

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. 我只想指出要小心,因为如果值不是唯一的,那么可能会导致数据丢失。 Fe if you have the following map: Fe如果你有以下地图:

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. 通过再次反转,您将有一个<key,value>对更少。

Iterate over the entrySet : 迭代entrySet

for ( Map.Entry<K, V> entry : map.entrySet() ) {
    newMap.put(entry.getValue(), entry.getKey());
}
return newMap;
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();
}

You may use any class that implements the "BidiMap" interface in the common collection from Apache ( http://commons.apache.org/collections/ ). 您可以在Apache的公共集合中使用任何实现“BidiMap”接口的类( 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM