我想编写一个方法,它将映射作为参数,并用值和键替换该映射的键和值。我正在尝试这样做:
public class HashMapKeyValueInterchange{
public static Map<String, String> getMyMap(ConcurrentHashMap<String, String> m){
Map<String, String> map2 = new HashMap<String, String>();
for(Entry<String, String> e:m.entrySet()){
map2.put(e.getValue(), e.getKey());
}
return map2;
}
public static void main(String[] args) {
ConcurrentHashMap<String, String> map1 = new ConcurrentHashMap<String, String>();
map1.put("ajay", "btech");
map1.put("manas", "mca");
map1.put("ashu", "mba");
}
}
使用此方法我可以获得一个带有交换的键和值的新 map (map2),但我希望交换map1
最佳答案
已经可用,无需重新发明轮子,如果你使用google集合库Guava那么你可以使用 BiMap<K,V>
.
It is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.
实现BiMap
是EnumBiMap, EnumHashBiMap, [HashBiMap][2], ImmutableBiMap
关于java - 如何用 Map 的值键替换键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18372109/