Java Program to Get key from HashMap Using the Value

Java Program to Get key from HashMap using the value

What is HashMap in Java ?

HashMap is a class in Java that implements the Map interface, providing a way to store key-value pairs. It uses a hash table to store the data, which allows for fast retrieval and insertion of elements. Keys are unique and are used to access corresponding values. It provides constant-time performance for the basic operations, such as adding, retrieving, and deleting elements.

Steps to Get key From HashMap Using Value :

Pseudo Code for the above algorithm :

function getKeyByValue(map, value):
    for each key-value pair in map:
        if value equals value of current key-value pair:
            return key of current key-value pair
    return null

Example : 

Run
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map< String, Integer > map = new HashMap<>();
        map.put("apple", 1);
        map.put("banana", 2);
        map.put("orange", 3);
        
        String key = getKeyByValue(map, 2);
        System.out.println(key); // prints "banana"
    }
    
    public static < K, V> K getKeyByValue(Map< K, V> map, V value) {
        for (Map.Entry< K, V> entry : map.entrySet()) {
            if (entry.getValue().equals(value)) {
                return entry.getKey();
            }
        }
        return null;
    }
}

Output :

banana

Example : 

Run
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map< Integer, String> map = new HashMap<>();
        map.put(1, "apple");
        map.put(2, "banana");
        map.put(3, "orange");

        int key = getKeyByValue(map, "banana");
        System.out.println(key); // prints "2"
    }

    public static < K, V> K getKeyByValue(Map  map, V value) {
        for (Map.Entry< K, V> entry : map.entrySet()) {
            if (entry.getValue().equals(value)) {
                return entry.getKey();
            }
        }
        return null;
    }
}

Output :

2

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription