Map 一组为key 一组为value

解决方案 »

  1.   

    能详细讲一下吗?
    hashmap可以按key搜索,但是不能按value搜索啊。难道是这样?
    put(A1,B1)
    ..
    put(A10,B10)
    put(B1,A1)
    ..
    put(B10,A10)
      

  2.   

    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
      

  3.   

    上面的“inverse view”是我想要的,但是就没有什么简单现成的解决方式吗?
      

  4.   

    用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();
    }

    if (en.getValue().equals(value)) {
    return en.getKey();
    }
    }
    return null;//没有找到
    }
    但这个如果数据量大的话可定效率不高
      

  5.   

    楼上的,谢谢你的回复。不过你的hashmap连get都不用,那用hashmap存储完全没有意义啊?
    我想过用hashmap,但是它只对key的检索优化,如果查找value,就要遍历hashmap,程序看起来不整洁。我很想知道大家是怎么解决这个问题的?如果没有好的答案,我就结贴了
      

  6.   

    你只想要JDK提供的?
    不是的话,使用Google提供的http://code.google.com/p/google-collections/