Java中的反向HashMap键和值 [英] Reverse HashMap keys and values in Java

查看:35
本文介绍了Java中的反向HashMap键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

推荐答案

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

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

或者,您可以使用双向地图,例如 Guava 提供和使用 inverse() 方法:

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

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

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

作为 出来了,你也可以这样:

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

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))

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

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:

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

这篇关于Java中的反向HashMap键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆