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