If I have the value \"foo\"
, and a HashMap
for which ftw.containsValue(\"foo\")
returns true
, how can I
If your data structure has many-to-one mapping between keys and values you should iterate over entries and pick all suitable keys:
public static Set getKeysByValue(Map map, E value) {
Set keys = new HashSet();
for (Entry entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
In case of one-to-one relationship, you can return the first matched key:
public static T getKeyByValue(Map map, E value) {
for (Entry entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
In Java 8:
public static Set getKeysByValue(Map map, E value) {
return map.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
Also, for Guava users, BiMap may be useful. For example:
BiMap tokenToChar =
ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);