Home >Java >javaTutorial >How to Retrieve Keys from a HashMap Given Its Values?
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; }</t></t></t></t></t>
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; }</t></t></t>
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()); }</t></t></t>
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);</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!