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!