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 */}
↧
Answer by Kanagavelu Sugumar for Java Hashmap: How to get key from value?
↧