If I have the value \"foo\"
, and a HashMap
for which ftw.containsValue(\"foo\")
returns true
, how can I
for(int key: hm.keySet()) {
if(hm.get(key).equals(value)) {
System.out.println(key);
}
}
Decorate map with your own implementation
class MyMap<K,V> extends HashMap<K, V>{
Map<V,K> reverseMap = new HashMap<V,K>();
@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);
}
}
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;
}
If you want to get key from value, its best to use bidimap (bi-directional maps) , you can get key from value in O(1) time.
But, the drawback with this is you can only use unique keyset and valueset.
There is a data structure called Table in java, which is nothing but map of maps like
Table< A, B , C > == map < A , map < B, C > >
Here you can get map<B,C>
by querying T.row(a);
, and you can also get map<A,C>
by querying T.column(b);
In your special case, insert C as some constant.
So, it like < a1, b1, 1 > < a2, b2 , 1 > , ...
So, if you find via T.row(a1) ---> returns map of --> get keyset this returned map.
If you need to find key value then, T.column(b2) --> returns map of --> get keyset of returned map.
Advantages over the previous case :
To find all the keys that map to that value, iterate through all the pairs in the hashmap, using map.entrySet()
.
Use a thin wrapper: HMap
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class HMap<K, V> {
private final Map<K, Map<K, V>> map;
public HMap() {
map = new HashMap<K, Map<K, V>>();
}
public HMap(final int initialCapacity) {
map = new HashMap<K, Map<K, V>>(initialCapacity);
}
public boolean containsKey(final Object key) {
return map.containsKey(key);
}
public V get(final Object key) {
final Map<K, V> entry = map.get(key);
if (entry != null)
return entry.values().iterator().next();
return null;
}
public K getKey(final Object key) {
final Map<K, V> entry = map.get(key);
if (entry != null)
return entry.keySet().iterator().next();
return null;
}
public V put(final K key, final V value) {
final Map<K, V> entry = map
.put(key, Collections.singletonMap(key, value));
if (entry != null)
return entry.values().iterator().next();
return null;
}
}