Algorithm


  1. Initialize the HashMap: Create a HashMap and add key-value pairs.

  2. Iterate through the HashMap Entries:

    • Use an iterator or a loop to traverse through the entries of the HashMap.
  3. Check for the Matching Value:

    • For each entry, compare the target value with the value of the current entry.
  4. Retrieve the Key:

    • If the values match, retrieve the key associated with that entry.
  5. Handle No Match:

    • If no match is found, handle the case appropriately (e.g., return a default value or indicate that no such key exists).

 

Code Examples

#1 Code Example- Get key for a given value in HashMap

Code - Java Programming

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;
      }
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
HashMap: {One=1, Two=2, Three=3}
The key for value 3 is Three
Advertisements

Demonstration


Java Programing Example to Get key from HashMap using the value-DevsEnv