Home >Java >javaTutorial >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; }
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; }
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()); }
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);
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!