Java program to get key from hashmap using the value
In Java, you can get a key from a HashMap
using the corresponding value. Here is an example program that demonstrates how to get a key from a HashMap
using the value:
import java.util.HashMap; import java.util.Map; public class GetKeyFromHashMap { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); map.put("pear", 4); int valueToFind = 3; String key = null; for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getValue().equals(valueToFind)) { key = entry.getKey(); break; } } if (key != null) { System.out.println("Key found: " + key); } else { System.out.println("Key not found for value: " + valueToFind); } } }
In this program, we define a HashMap
that maps String
keys to Integer
values. We then add some key-value pairs to the HashMap
. We want to find the key corresponding to the value 3. To do this, we loop through the HashMap
entries using a for-each loop. For each entry, we check if the value equals the value we're looking for. If it does, we store the corresponding key in a variable called key
. We then break out of the loop, since we only need to find the first key that corresponds to the value we're looking for.
After the loop, we check if key
is null
. If it's not, we print out the key that corresponds to the value we were looking for. Otherwise, we print out a message indicating that the key was not found for the given value.
When you run this program, you should get output like this:
Key found: orange
This shows that the program correctly found the key that corresponds to the value 3.