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

Answer by Vitalii Fedorenko for Java Hashmap: How to get key from value?

$
0
0

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 <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {    Set<T> keys = new HashSet<T>();    for (Entry<T, E> 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, E> T getKeyByValue(Map<T, E> map, E value) {    for (Entry<T, E> entry : map.entrySet()) {        if (Objects.equals(value, entry.getValue())) {            return entry.getKey();        }    }    return null;}

In Java 8:

public static <T, E> Set<T> getKeysByValue(Map<T, E> 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<Token, Character> tokenToChar =     ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');Token token = tokenToChar.inverse().get('(');Character c = tokenToChar.get(token);

Viewing all articles
Browse latest Browse all 41

Trending Articles