Dan*_*jel 79 java map apache-commons guava
我在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);
Run Code Online (Sandbox Code Playgroud)
有没有正确的方法来实现这两个方向?
另一个问题是我只有一些不会改变的常数值(1->"low", 2->"mid", 3->"high"因此,找一个复杂的解决方案是不值得的.
Mic*_*d a 37
创建Guava BiMap并获得倒置值并非如此微不足道.
简单的例子:
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"));
}
}
Run Code Online (Sandbox Code Playgroud)
Chi*_*itz 10
您可以将键,值对及其反转插入到地图结构中,但必须将整数转换为字符串:
map.put("theKey", "theValue");
map.put("theValue", "theKey");
Run Code Online (Sandbox Code Playgroud)
然后使用map.get("theValue")将返回"theKey".
这是一种快速而肮脏的方式,我制作了恒定的地图,这只适用于少数几个数据集:
如果你想保持<Integer, String>你可以保持第二个<String, Integer>地图"放"值 - >密钥对.
| 归档时间: |
|
| 查看次数: |
83076 次 |
| 最近记录: |