Google Collections 提供了BiMap(接口),HashBiMap(内部有2个HashMap) 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.http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html
上面的“inverse view”是我想要的,但是就没有什么简单现成的解决方式吗?
用HashMap啊查找思路如下: public String getValue(Map<String, String> map, String value) { for (Iterator <Entry<String, String>> it = map.entrySet().iterator(); it.hasNext();) { Entry<String, String> en = it.next(); if (en.getKey().equals(value)) { return en.getValue(); }
hashmap可以按key搜索,但是不能按value搜索啊。难道是这样?
put(A1,B1)
..
put(A10,B10)
put(B1,A1)
..
put(B10,A10)
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.http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html
public String getValue(Map<String, String> map, String value) {
for (Iterator <Entry<String, String>> it = map.entrySet().iterator(); it.hasNext();) {
Entry<String, String> en = it.next();
if (en.getKey().equals(value)) {
return en.getValue();
}
if (en.getValue().equals(value)) {
return en.getKey();
}
}
return null;//没有找到
}
但这个如果数据量大的话可定效率不高
我想过用hashmap,但是它只对key的检索优化,如果查找value,就要遍历hashmap,程序看起来不整洁。我很想知道大家是怎么解决这个问题的?如果没有好的答案,我就结贴了
不是的话,使用Google提供的http://code.google.com/p/google-collections/