Java: How to get all Keys by a Value in HashMap ? | Search by Value in Map

HashMap has been a part of the Java collection since Java 1.2. This class are often found within the java.util package. It implements the Java Map interface in its most basic form. It stores the data in (Key, Value) pairs that can be accessed via an index of another type (e.g. an Integer). One object serves as a key (index) to another (value). If you are trying to insert a replica key, it’ll replace the corresponding key’s element.

HashMaps are similar to HashTables, but they are not synchronised. It also allows for the storage of null keys, but there should only be one null key object and any number of null values. This class makes no guarantees about the map’s order. You must import java.util to use this class and its methods. HashMap’s superclass or the HashMap package
In this article, we will look at how to search a Map by value and retrieve the keys that correspond to the given value.

Examples:

Input:

hashmap={"hello" : 2
                  "this" : 3
                  "BTechGeeks" :4
                 "Python" : 2
                 "Online" : 5
                 "Platform" : 2}
value =2

Output:

[Platform, hello, Python]

Get all Keys by a Value in HashMap

Follow these steps to get the keys associated with a given value.

First and foremost Using the containsValue() function, determine whether a given value exists in the map. If yes, iterate over a given Map and for each Entry, check if the value matches the given value, and if so, store the key in the list.
Generic solution for all maps, e.g. HashMap, TreeMap, etc.

Below is the implementation:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Codechef {
    static <K, V> List<K> getAllKeys(Map<K, V> wordsmap,
                                     V given_value)
    {
        List<K> keyslist = null;

        // checking if thee given hashmap contains given
        // value
        if (wordsmap.containsValue(given_value)) {
            // creating a new empty list
            keyslist = new ArrayList<>();

            // Using entrySet, iterate over each map entry.
            for (Map.Entry<K, V> entryvalue :
                 wordsmap.entrySet()) {
                // Examine the value to see if it matches the given value.
                if (entryvalue.getValue().equals(
                        given_value)) {
                    // Examine the value to see if it matches the given value.
                    keyslist.add(entryvalue.getKey());
                }
            }
        }
        // Return a list of keys whose values are the same
        // as the given value.
        return keyslist;
    }
    public static void main(String[] args)
        throws java.lang.Exception
    {

        // Make a word map with a frequency count.
        HashMap<String, Integer> wordsmap
            = new HashMap<String, Integer>() {
                  {

                      put("hello", 2);
                      put("this", 3);
                      put("BTechGeeks", 4);
                      put("Python", 2);
                      put("Online", 5);
                      put("Platform", 2);
                  }
              };
        // Get a list of keys with the same value as the
        // given value.
        List<String> keyslist
            = Codechef.getAllKeys(wordsmap, 2);
        System.out.println(keyslist);
    }
}

Output:

[Platform, hello, Python]

Related Programs: