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

How to Retrieve Keys from a HashMap Given Its Values?

Susan Sarandon
Susan SarandonOriginal
2024-12-18 08:46:10794browse

How to Retrieve Keys from a HashMap Given Its Values?

Retrieving Keys from HashMaps Based on Values

Given a HashMap with values stored against keys, let's explore how to retrieve the key corresponding to a specific value.

Value-to-Multiple Keys:

If a key-value pair can map to multiple values, you'll need to iterate through the entries and filter those with the desired value:

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

Value-to-Single Key:

If there's a one-to-one mapping between keys and values, you can directly 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:

With Java 8 streams, you can filter and map entries more efficiently:

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 BiMap:

If you're using Guava, the BiMap collection provides a more convenient way to work with inverse 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 a HashMap Given Its Values?. 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