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

标签 java

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

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/

相关文章:

java - TextToSpeech setLanguage 不起作用?

java - Node.getNodeValue() 在 java 中返回 null

java - 找不到获取 Spring bean 方法参数的参数化类型的方法

java - 提取jms文本内容

java - 为什么我的 Connect 4 程序中出现 NullPointerException?

java - Alpha 混合在 Android libgdx 上不起作用,但在桌面上起作用

java - 向上导航确认

java - ArrayList 对象 - 构造函数如何工作,它们的时间复杂度是多少?

java - 字符串包含相同的字符但仍然不同

java - 地理位置谷歌地图 v2