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

How to Retrieve Keys from HashMap Values in Java?

Barbara Streisand
Release: 2024-12-14 08:52:11
Original
271 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template