Write a Java Program to Get key from HashMap using the Value

In Java, HashMap is a widely used collection class that stores data in key-value pairs.

The HashMap allows you to store and retrieve data quickly and efficiently.

However, in some cases, you may want to get the key from the HashMap based on a given value.

In this tutorial, we will explore how to get a key from a HashMap using the value in Java.


Understanding HashMap in Java

HashMap is a data structure that implements the Map interface.

It stores data in key-value pairs, where each key must be unique.

HashMap is based on a hash table, which provides fast access to data.

To store data in a HashMap, you need to create an instance of the HashMap class and use the put() method to add elements to the HashMap.

Example:

HashMap map = new HashMap<>();
map.put("John", 25);
map.put("Jane", 30);
map.put("Mike", 35);

In the example above, we have created a HashMap that stores the age of three people.

The key is a String that represents the person’s name, and the value is an Integer that represents their age.

Getting a Key from HashMap using the Value

To get the key from the HashMap based on a given value, you need to iterate over the HashMap using a for loop or a foreach loop.

Inside the loop, you can check if the current value is equal to the value you are searching for. If it is, you can return the key.

Here’s an example:

public static K getKey(HashMap map, V value) {
for (K key : map.keySet()) {
if (value.equals(map.get(key))) {
return key;
}
}
return null;
}

In the example above, we have created a method called getKey() that takes a HashMap and a value as input parameters.

The method iterates over the HashMap and checks if the value of the current key is equal to the given value.

If it is, the method returns the key. If the value is not found in the HashMap, the method returns null.

Example usage:

HashMap map = new HashMap<>();
map.put("John", 25);
map.put("Jane", 30);
map.put("Mike", 35);

String name = getKey(map, 30);
System.out.println(name); // Output: Jane

In the example above, we have called the getKey() method with the HashMap and the value of 30.

The method has returned the key “Jane”, which is the name of the person who is 30 years old.


Conclusion

HashMap is a powerful collection class that provides fast access to data in Java.

In some cases, you may want to get the key from the HashMap based on a given value.

In this tutorial, we have explored how to get a key from a HashMap using the value in Java.

We have created a method that iterates over the HashMap and returns the key if the value matches the given value.

This method can be used in a wide range of scenarios where you need to retrieve data from a HashMap based on its value.