Home > Java > javaTutorial > How to Find Keys Associated with Specific Values in a HashMap?

How to Find Keys Associated with Specific Values in a HashMap?

Susan Sarandon
Release: 2024-12-18 22:38:11
Original
955 people have browsed it

How to Find Keys Associated with Specific Values in a HashMap?

Finding Keys Associated with Values in HashMap

When working with hashmaps, it's often necessary to retrieve keys based on specific values. There are several approaches to accomplish this task in Java.

One option is to iterate through the HashMap's entrySet() and compare each entry's value to the desired one:

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

If you expect a one-to-one relationship between keys and values, you can retrieve 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

In Java 8, you can leverage 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

Alternatively, for situations with bi-directional mappings, the Guava library provides BiMap which offers direct key-value lookups and vice-versa. For instance:

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 Find Keys Associated with Specific Values in a 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