Java Program to Get key from HashMap using the value

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Get key for a given value in HashMap

import java.util.HashMap;
import java.util.Map.Entry;

class Main {
  public static void main(String[] args) {

    // create a hashmap
    HashMap<String, Integer> numbers = new HashMap<>();
    numbers.put("One", 1);
    numbers.put("Two", 2);
    numbers.put("Three", 3);
    System.out.println("HashMap: " + numbers);

    // value whose key is to be searched
    Integer value = 3;

    // iterate each entry of hashmap
    for(Entry<String, Integer> entry: numbers.entrySet()) {

      // if give value is equal to value from entry
      // print the corresponding key
      if(entry.getValue() == value) {
        System.out.println("The key for value " + value + " is " + entry.getKey());
        break;
      }
    }
  }
}

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.

Did you find this article helpful?