我在 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/