Java中的双向地图? [英] Bi-directional Map in Java?

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

问题描述

我在 Java 中有一个简单的整数到字符串的映射,但我需要能够轻松地从整数中检索字符串,以及从字符串中检索整数.我试过 Map,但它只能从整数中检索字符串,这是一种方法:

I have a simple integer-to-string mapping in Java, but I need to be able to easily retrieve string from integer, and also integer from string. I've tried Map, but it can retrieve only string from integer, it's one way:

private static final Map<Integer, String> myMap = new HashMap<Integer, String>();
// This works one way:
String myString = myMap.get(myInteger);

// I would need something like:
Integer myInteger = myMap.getKey(myString);

有没有正确的方法可以做到双向?

Is there a right way to do it to have it both directions?

另一个问题是我只有几个不变的值(1->"low", 2->"mid", 3->"high",因此不值得采用复杂的解决方案.

Another problem is that I only have a few constant values that don't change (1->"low", 2->"mid", 3->"high", so it wouldn't be worth to go for a complicated solution.

推荐答案

您可以为此使用 Google Collections API,最近 更名为 Guava,特别是 BiMap一个>

You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap

双映射(或双向映射")是一种保留其值及其键的唯一性.这个约束使 bimap 能够支持反向视图",这是另一个 bimap包含与此 bimap 相同的条目,但具有相反的键和价值.

A bimap (or "bidirectional map") 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.

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

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