Home >Java >javaTutorial >How to Retrieve Keys from HashMap Values in Java?

How to Retrieve Keys from HashMap Values in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 08:52:11275browse

How to Retrieve Keys from HashMap Values in Java?

Retrieving Keys from HashMap Values

In Java, when working with Hashmaps, there may arise situations where you have a value and wish to obtain its corresponding key. To accomplish this, several methods are available.

Looping Through Entries

The simplest approach involves iterating over all entries in the HashMap:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    Set<T> keys = new HashSet<>();
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            keys.add(entry.getKey());
        }
    }
    return keys;
}

Returning the First Matched Key

If you have a one-to-one mapping, you can return the first matching 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;
}

Using Java 8 Streams

For Java 8 users, you can utilize streams for more concise code:

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());
}

Guava's BiMap

If you prefer using Guava, consider using its BiMap for bidirectional mappings:

BiMap<Token, Character> tokenToChar = 
    ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);

The above is the detailed content of How to Retrieve Keys from HashMap Values in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn