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

How Can I Retrieve Keys from Values in a Java HashMap?

Linda Hamilton
Release: 2024-12-15 21:15:20
Original
499 people have browsed it

How Can I Retrieve Keys from Values in a Java HashMap?

Retrieving Keys from Values in Java HashMap

HashMap is a valuable Java data structure for storing key-value pairs. While retrieving values from keys is straightforward, retrieving keys from values can be more challenging. Here are several efficient methods to achieve this:

One-to-Many Mappings

In situations where multiple keys can map to a single value, you can iterate over the HashMap's entries and collect all matching keys:

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

One-to-One Mappings

When each value maps to a unique key, 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;
}
Copy after login

Java 8 Stream Approach

Java 8 provides a convenient method for filtering and collecting matching 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

For cases where the bi-directional mapping is required, consider using Guava's BiMap:

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 Can I 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