如果我有值“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;
}

其他回答

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

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

/**
 * 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;
}

您可以将键、值对及其逆函数插入到映射结构中

map.put("theKey", "theValue");
map.put("theValue", "theKey");

使用map.get("theValue")将返回"theKey"。

这是一种快速而肮脏的方法,我已经创建了常量映射,它只适用于少数数据集:

只能包含1 ~ 1对 值集与键集不相交(1-> 2,2 ->3中断它)

如果你想从value中获取key,最好使用bidimap(双向映射),你可以在O(1)时间内从value中获取key。 但是,这样做的缺点是你只能使用唯一的键集和值集。 在java中有一个数据结构叫Table,它就是map of maps 表< A, B, C > == map < A, map < B, C > > 这里通过查询T.row(a);可以得到map<B,C>,通过查询T.column(B);也可以得到map< a,C>;

在你的特殊情况下,插入C作为某个常数。

它是< a1, b1, 1 > < a2, b2, 1 >,…

如果你通过t。row(a1)——>返回——>的map get keyset这个返回的map。

如果你需要找到键值,那么T.column(b2)——>返回map of——> get keyset of返回map。

与前一种情况相比的优点:

可以使用多个值。 在使用大型数据集时效率更高。

public static class SmartHashMap <T1 extends Object, T2 extends Object> {
    public HashMap<T1, T2> keyValue;
    public HashMap<T2, T1> valueKey;

    public SmartHashMap(){
        this.keyValue = new HashMap<T1, T2>();
        this.valueKey = new HashMap<T2, T1>();
    }

    public void add(T1 key, T2 value){
        this.keyValue.put(key, value);
        this.valueKey.put(value, key);
    }

    public T2 getValue(T1 key){
        return this.keyValue.get(key);
    }

    public T1 getKey(T2 value){
        return this.valueKey.get(value);
    }

}
for(int key: hm.keySet()) {
    if(hm.get(key).equals(value)) {
        System.out.println(key); 
    }
}