gpt4 book ai didi

java - 如何用 Map 的值键替换键值

转载 作者:行者123 更新时间:2023-12-02 06:48:08 24 4
gpt4 key购买 nike

我想编写一个方法,它将映射作为参数,并用值和键替换该映射的键和值。我正在尝试这样做:

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.

实现BiMapEnumBiMap, EnumHashBiMap, [HashBiMap][2], ImmutableBiMap

关于java - 如何用 Map 的值键替换键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18372109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com