Write a Java program to get keys from the hashmap using the value.
In this tutorial, you will learn Java examples to get keys from a HashMap based on a defined value.
Get Key for a Value in HashMap
Create a file HashMapExample1.java in your system and add the below content.
import java.util.HashMap;
import java.util.Map.Entry;
class HashMapExample1 {
public static void main(String[] args) {
// Define a hashmap
HashMap<Integer, String> cities = new HashMap<>();
// Adding key pair to hashmap
cities.put(101, "Delhi");
cities.put(102, "New York");
cities.put(103, "Peris");
cities.put(104, "Denmark");
// Define value to search key for
String value = "Peris";
// Iterate through hashmap using for loop
for(Entry<Integer, String> entry: cities.entrySet()) {
if(entry.getValue() == value) {
System.out.println("The Key for '" + value + "' is " + entry.getKey());
break;
}
}
}
}
Save the file and close it.
Now, compile the Java program and run. You will see the results below.
Get All Key Values in HashMap
Here is another example showing to get all key values from a Java HashMap.
import java.util.HashMap;
import java.util.Map.Entry;
class HashmapExample2 {
public static void main(String[] args) {
// Define a hashmap
HashMap<Integer, String> cities = new HashMap<>();
// Adding key pair to hashmap
cities.put(101, "Delhi");
cities.put(102, "New York");
cities.put(103, "Peris");
cities.put(104, "Denmark");
// Print all hashmap key pairs
System.out.println("HashMap: " + cities);
}
}
Now, compile and run above Java program. You should see the results as below:
Tags
Java