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


当前回答

public static String getKey(Map<String, Integer> mapref, String value) {
    String key = "";
    for (Map.Entry<String, Integer> map : mapref.entrySet()) {
        if (map.getValue().toString().equals(value)) {
            key = map.getKey();
        }
    }
    return key;
}

其他回答

我认为你的选择是

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.

据我所知,当你将HashMap的键和值表示为数组时,它们是不混合的:

hashmap.values().toArray()

and

hashmap.keySet().toArray()

所以下面的代码(从java 8开始)应该像预期的那样工作:

public Object getKeyByFirstValue(Object value) {
    int keyNumber =  Arrays.asList(hashmap.values().toArray()).indexOf(value);
    return hashmap.keySet().toArray()[keyNumber];
}

然而,(警告!)它的工作速度比迭代慢2-3倍。

听起来最好的方法是使用map.entrySet()来遍历条目,因为map.containsValue()可能会这样做。

虽然这并没有直接回答问题,但它是相关的。

这样你就不需要继续创建/迭代了。只需创建一个反向映射一次,就可以得到你需要的东西。

/**
 * Both key and value types must define equals() and hashCode() for this to work.
 * This takes into account that all keys are unique but all values may not be.
 *
 * @param map
 * @param <K>
 * @param <V>
 * @return
 */
public static <K, V> Map<V, List<K>> reverseMap(Map<K,V> map) {
    if(map == null) return null;

    Map<V, List<K>> reverseMap = new ArrayMap<>();

    for(Map.Entry<K,V> entry : map.entrySet()) {
        appendValueToMapList(reverseMap, entry.getValue(), entry.getKey());
    }

    return reverseMap;
}


/**
 * Takes into account that the list may already have values.
 * 
 * @param map
 * @param key
 * @param value
 * @param <K>
 * @param <V>
 * @return
 */
public static <K, V> Map<K, List<V>> appendValueToMapList(Map<K, List<V>> map, K key, V value) {
    if(map == null || key == null || value == null) return map;

    List<V> list = map.get(key);

    if(list == null) {
        List<V> newList = new ArrayList<>();
        newList.add(value);
        map.put(key, newList);
    }
    else {
        list.add(value);
    }

    return map;
}

找到了太多答案。有些真的很棒。但我特别在寻找一种方法,这样我就可以用循环得到值。

这就是我最后做的: 对于HashMap 1对1关系:

    Map<String, String> map = new HashMap<String, String>();
    
    map.put("abc", "123");
    map.put("xyz", "456");
    
    for(Entry<String, String> entry : map.entrySet()) {
        if(entry.getValue().equalsIgnoreCase("456")) {
            System.out.println(entry.getKey());
        }
    }

输出:“xyz”

对于HashMap一对多关系:

    Map<String, ArrayList<String>> service = new HashMap<String, ArrayList<String>>();
    
    service.put("abc", new ArrayList<String>());
    service.get("abc").add("a");
    service.get("abc").add("b");
    service.get("abc").add("c");
    
    service.put("xyz", new ArrayList<String>());
    service.get("xyz").add("x");
    service.get("xyz").add("y");
    service.get("xyz").add("z");
    
    for(Entry<String, ArrayList<String>> entry : service.entrySet()) {
        ArrayList<String> values = entry.getValue();
        for(String value : values) {
            if(value.equalsIgnoreCase("x")) {
                System.out.println(entry.getKey());
            }
        }
        
    }

输出:xyz

-谢谢