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

How to Retrieve Keys from Values in a Java HashMap?

Barbara Streisand
Release: 2024-12-19 08:59:09
Original
394 people have browsed it

How to Retrieve Keys from Values in a Java HashMap?

Retrieving Keys from Values in Java Hashmaps

In a Java HashMap, retrieving the key corresponding to a specific value can be useful in various scenarios. Here's a comprehensive exploration of how to accomplish this task:

Loop-Based Approach:

The traditional method for obtaining the key from a value is to iterate through the HashMap's entries. For each entry, compare the value to the desired one. If a match is found, the corresponding key can be retrieved.

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

Key Retrieval for One-to-One Mappings:

In scenarios where each value maps to only one key, the loop-based approach can be simplified to 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;
}
Copy after login

Java 8 Stream Approach:

For Java 8 and above users, stream operations can provide a concise way to retrieve keys.

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:

Alternatively, for users of the Guava library, the BiMap data structure can be particularly useful. It provides a bi-directional mapping between keys and values, allowing for efficient retrieval of both keys and values.

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 Values in a Java HashMap?. 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