如果我有值“foo”,和一个HashMap<String> ftw,其中ftw. containsvalue(“foo”)返回真,我怎么能得到相应的键?我需要遍历hashmap吗?最好的方法是什么?


当前回答

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class M{
public static void main(String[] args) {

        HashMap<String, List<String>> resultHashMap = new HashMap<String, List<String>>();

        Set<String> newKeyList = resultHashMap.keySet();


        for (Iterator<String> iterator = originalHashMap.keySet().iterator(); iterator.hasNext();) {
            String hashKey = (String) iterator.next();

            if (!newKeyList.contains(originalHashMap.get(hashKey))) {
                List<String> loArrayList = new ArrayList<String>();
                loArrayList.add(hashKey);
                resultHashMap.put(originalHashMap.get(hashKey), loArrayList);
            } else {
                List<String> loArrayList = resultHashMap.get(originalHashMap
                        .get(hashKey));
                loArrayList.add(hashKey);
                resultHashMap.put(originalHashMap.get(hashKey), loArrayList);
            }
        }

        System.out.println("Original HashMap : " + originalHashMap);
        System.out.println("Result HashMap : " + resultHashMap);
    }
}

其他回答

我的2分钱。 您可以获取数组中的键,然后循环遍历数组。如果映射非常大,这将影响代码块的性能,因为首先获取数组中的键可能会消耗一些时间,然后再进行循环。否则,对于较小的地图,这应该是可以的。

String[] keys =  yourMap.keySet().toArray(new String[0]);

for(int i = 0 ; i < keys.length ; i++){
    //This is your key    
    String key = keys[i];

    //This is your value
    yourMap.get(key)            
}

没有明确的答案,因为多个键可以映射到相同的值。如果要在自己的代码中强制执行唯一性,最好的解决方案是创建一个类,该类使用两个hashmap在两个方向上跟踪映射。

要找到映射到该值的所有键,请使用map. entryset()遍历hashmap中的所有对。

需要注意的是,由于这个问题,Apache Collections支持通用的BidiMaps。因此,一些投票最多的答案在这一点上不再准确。

对于支持重复值(一对多场景)的Serialized BidiMap,也可以考虑MapDB.org。

我认为你的选择是

Use a map implementation built for this, like the BiMap from google collections. Note that the google collections BiMap requires uniqueless of values, as well as keys, but it provides high performance in both directions performance Manually maintain two maps - one for key -> value, and another map for value -> key Iterate through the entrySet() and to find the keys which match the value. This is the slowest method, since it requires iterating through the entire collection, while the other two methods don't require that.