java - Java中的双向 map ?

标签 java map guava apache-commons

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

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

有没有正确的方法来做到这两个方向?

另一个问题是我只有几个不变的值(1->"low", 2->"mid", 3->"high",所以它不值得去寻求一个复杂的解决方案。

最佳答案

您可以为此使用 Google Collections API,最近 重命名为 Guava ,特别是 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 - Java中的双向 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10699492/

相关文章:

java - PowerMock:来自父类的 stub 方法

java - 读取java进程的输入流

map - 在 Windows Phone 8 上更改 map 控件上的语言

map - 在 D2 中将 std.algorithm.map 与成员函数一起使用

java - Sonar 问题 - 参数必须为非空但标记为可为空

gwt - 使用与 GWT 捆绑的 Guava

java - 仅在一个目录的命令行中设置 Java 路径

java - 如何在简单的规则中使用变量?

scala - 如何在Scala中将对象列表转换为两个字段的映射

java - 如何确保多个 Guava 缓存不互相锁定?