If I have the value \"foo\"
, and a HashMap
for which ftw.containsValue(\"foo\")
returns true
, how can I
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;
}