Java 中的反向 HashMap 键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20412354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:46:29  来源:igfitidea点击:

Reverse HashMap keys and values in Java

javahashmap

提问by Ken

It's a simple question, I have a simple HashMap of which i want to reverse the keys and values.

这是一个简单的问题,我有一个简单的 HashMap,我想反转它的键和值。

HashMap<Character, String> myHashMap = new HashMap<Character, String>();
myHashMap.put('a', "test one");
myHashMap.put('b', "test two");

and I want to create a new HashMap in which i put the opposites.

我想创建一个新的 HashMap,在其中放置对立面。

HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
e.g. Keys "test one" & "test two" and values 'a' & 'b'.

采纳答案by Alexis C.

They all are unique, yes

他们都是独一无二的,是的

If you're sure that your values are unique you can iterate over the entries of your old map .

如果您确定您的值是唯一的,您可以迭代旧 map 的条目。

Map<String, Character> myNewHashMap = new HashMap<>();
for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
    myNewHashMap.put(entry.getValue(), entry.getKey());
}

Alternatively, you can use a Bi-Directional map like Guavaprovides and use the inverse()method :

或者,您可以使用像Guava提供的双向地图并使用inverse()方法:

BiMap<Character, String> myBiMap = HashBiMap.create();
myBiMap.put('a', "test one");
myBiMap.put('b', "test two");

BiMap<String, Character> myBiMapInversed = myBiMap.inverse();

As java-8is out, you can also do it this way :

由于java-8出来了,你也可以这样做:

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, String> mapInversed = 
    map.entrySet()
       .stream()
       .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))

Finally, I added my contribution to the proton pack library, which contains utility methods for the Stream API. With that you could do it like this:

最后,我将我的贡献添加到质子包库中,其中包含 Stream API 的实用方法。有了它,你可以这样做:

Map<Character, String> mapInversed = MapStream.of(map).inverseMapping().collect();

回答by hichris123

Iterate through the list of keys and values, then add them.

遍历键和值列表,然后添加它们。

HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (String key : myHashMap.keySet()){
    reversedHashMap.put(myHashMap.get(key), key);
}

回答by A4L

To answer your question on how you can do it, you could get the entrySetfrom your map and then just put into the new map by using getValueas keyand getKeyas value.

要回答有关如何执行此操作的问题,您可以从地图中获取entrySet,然后使用getValueaskeygetKeyas将其放入新地图中value

But remember that keys in a Mapare unique, which means if you have one value with two different key in your original map, only the second key (in iteration order) will be kep as value in the new map.

但是请记住Map中的键是唯一的,这意味着如果您的原始映射中有一个值具有两个不同的键,则只有第二个键(按迭代顺序)将作为新映射中的值保留。

回答by Ken

I wrote a simpler loop that works too (note that all my values are unique):

我写了一个更简单的循环,它也有效(请注意,我的所有值都是唯一的):

HashMap<Character, String> myHashMap = new HashMap<Character, String>();
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();

for (char i : myHashMap.keySet()) {
    reversedHashMap.put(myHashMap.get(i), i);
}

回答by Riju Thomas

Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique

Apache 公共集合库提供了一种用于反转地图的实用方法。如果您确定 myHashMap 的值是唯一的,则可以使用它

org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)

Sample code

示例代码

HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap) 

回答by Mark Hetherington

private <A, B> Map<B, A> invertMap(Map<A, B> map) {
    Map<B, A> reverseMap = new HashMap<>();
    for (Map.Entry<A, B> entry : map.entrySet()) {
        reverseMap.put(entry.getValue(), entry.getKey());
    }
    return reverseMap;
}

It's important to remember that putreplaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.

重要的是要记住,put使用相同的键调用时会替换值。因此,如果您的映射具有两个具有相同值的键,则倒置映射中将仅存在其中一个键。

回答by mob

If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function

如果值不唯一,则反转映射的安全方法是使用 java 8 的 groupingBy 函数

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, List<String>> mapInversed = 
map.entrySet()
   .stream()
   .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))

回答by Deepak Arora

Tested with below sample snippet, tried with MapUtils, and Java8 Stream feature. It worked with both cases.

使用以下示例片段进行测试,尝试使用 MapUtils 和 Java8 Stream 功能。它适用于两种情况。

public static void main(String[] args) {
    Map<String, String> test = new HashMap<String, String>();
    test.put("a", "1");
    test.put("d", "1");
    test.put("b", "2");
    test.put("c", "3");
    test.put("d", "4");
    test.put("d", "41");

    System.out.println(test);

    Map<String, String> test1 = MapUtils.invertMap(test);

    System.out.println(test1);

    Map<String, String> mapInversed = 
            test.entrySet()
               .stream()
               .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));

    System.out.println(mapInversed);
}

Output:
{a=1, b=2, c=3, d=41}
{1=a, 2=b, 3=c, 41=d}
{1=a, 2=b, 3=c, 41=d}