Java 语言中的双向映射? ?

我在 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",所以不值得去寻找一个复杂的解决方案。

125423 次浏览

You can use the Google Collections API for that, recently renamed to Guava, specifically a 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.

There is no bidirectional map in the Java Standard API. Either you can maintain two maps yourself or use the BidiMap from Apache Collections.

Apache commons collections has a BidiMap

Use Google's BiMap

It is more convenient.

Creating a Guava BiMap and getting its inverted values is trivial.

A simple example:

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;


public class BiMapTest {


public static void main(String[] args) {


BiMap<String, String> biMap = HashBiMap.create();


biMap.put("k1", "v1");
biMap.put("k2", "v2");


System.out.println("k1 = " + biMap.get("k1"));
System.out.println("v2 = " + biMap.inverse().get("v2"));
}
}

You could insert both the key,value pair and its inverse into your map structure, but would have to convert the Integer to a string:

map.put("theKey", "theValue");
map.put("theValue", "theKey");

Using map.get("theValue") will then return "theKey".

It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:

  • Contains only 1 to 1 pairs
  • Set of values is disjoint from the set of keys (1->2, 2->3 breaks it)

If you want to keep <Integer, String> you could maintain a second <String, Integer> map to "put" the value -> key pairs.