Java Hashmap: How to get key from value?

前端 未结 30 1829
忘掉有多难
忘掉有多难 2020-11-22 02:14

If I have the value \"foo\", and a HashMap ftw for which ftw.containsValue(\"foo\") returns true, how can I

30条回答
  •  囚心锁ツ
    2020-11-22 03:17

    While this does not directly answer the question, it is related.

    This way you don't need to keep creating/iterating. Just create a reverse map once and get what you need.

    /**
     * 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 
     * @param 
     * @return
     */
    public static  Map> reverseMap(Map map) {
        if(map == null) return null;
    
        Map> reverseMap = new ArrayMap<>();
    
        for(Map.Entry 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 
     * @param 
     * @return
     */
    public static  Map> appendValueToMapList(Map> map, K key, V value) {
        if(map == null || key == null || value == null) return map;
    
        List list = map.get(key);
    
        if(list == null) {
            List newList = new ArrayList<>();
            newList.add(value);
            map.put(key, newList);
        }
        else {
            list.add(value);
        }
    
        return map;
    }
    

提交回复
热议问题