Retrieving Keys from HashMap Values
In Java, when working with Hashmaps, there may arise situations where you have a value and wish to obtain its corresponding key. To accomplish this, several methods are available.
Looping Through Entries
The simplest approach involves iterating over all entries in the HashMap:
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; }
Returning the First Matched Key
If you have a one-to-one mapping, you can 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
For Java 8 users, you can utilize 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()); }
Guava's BiMap
If you prefer using Guava, consider using its BiMap for bidirectional 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 HashMap Values in Java?. For more information, please follow other related articles on the PHP Chinese website!