Example: Get key for a given value in HashMap
Output
HashMap: {One=1, Two=2, Three=3}
The key for value 3 is Three
In the above example, we have created a hashmap named numbers. Here, we want to get the key for the value 3. Notice the line,
Entry<String, Integer> entry : numbers.entrySet()
Here, the entrySet() method returns a set view of all the entries.
- entry.getValue() - get value from the entry
- entry.getKey() - get key from the entry
Inside the if statement we check if the value from the entry is the same as the given value. And, for matching value, we get the corresponding key.