Quantcast
Channel: Java Hashmap: How to get key from value? - Stack Overflow
Viewing all articles
Browse latest Browse all 41

Answer by Kanagavelu Sugumar for Java Hashmap: How to get key from value?

$
0
0
import java.util.HashMap;import java.util.HashSet;import java.util.Set;public class ValueKeysMap<K, V> extends HashMap <K,V>{    HashMap<V, Set<K>> ValueKeysMap = new HashMap<V, Set<K>>();    @Override    public boolean containsValue(Object value) {        return ValueKeysMap.containsKey(value);    }    @Override    public V put(K key, V value) {        if (containsValue(value)) {            Set<K> keys = ValueKeysMap.get(value);            keys.add(key);        } else {            Set<K> keys = new HashSet<K>();            keys.add(key);            ValueKeysMap.put(value, keys);        }        return super.put(key, value);    }    @Override    public V remove(Object key) {        V value = super.remove(key);        Set<K> keys = ValueKeysMap.get(value);        keys.remove(key);        if(keys.size() == 0) {           ValueKeysMap.remove(value);        }        return value;    }    public Set<K> getKeys4ThisValue(V value){        Set<K> keys = ValueKeysMap.get(value);        return keys;    }    public boolean valueContainsThisKey(K key, V value){        if (containsValue(value)) {            Set<K> keys = ValueKeysMap.get(value);            return keys.contains(key);        }        return false;    }    /*     * Take care of argument constructor and other api's like putAll     */}

Viewing all articles
Browse latest Browse all 41

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>