Java Hashmap: How to get key from value?

前端 未结 30 2234
忘掉有多难
忘掉有多难 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:01

    Decorate map with your own implementation

    class MyMap extends HashMap{
    
        Map reverseMap = new HashMap();
    
        @Override
        public V put(K key, V value) {
            // TODO Auto-generated method stub
            reverseMap.put(value, key);
            return super.put(key, value);
        }
    
        public K getKey(V value){
            return reverseMap.get(value);
        }
    }
    

提交回复
热议问题