Java – How to get Keys from Value in HashMap ?

In this article, we will discuss how to get Keys from Value in Map or Map implemented classes like HashMap, LinkedHashMap or TreeMap

Before diving into the implementation details of getting Keys from Value in HashMap, we need to understand the properties of HashMap in detail

1. HashMap :

  • It is the direct implementation class of Map interface (i.e.; HashMap implements Map)
  • It uses hashtable to store KeyValue pairs (which is also known as Map entries)
  • Keys :
    • allows only unique keys
    • allows NULL insertion for a maximum of one
  • Values :
    • values can be duplicated
    • allows NULL insertion without any upperlimit
  • Insertion-order is not maintained

2. Get Keys from Value :

Since same value (duplicate) can be assigned to any number of keys, it is possible to get multiple Keys for the passed value. We will get Keys from Value using 2 different approaches,

2.1 Using keySet() method of Map interface :

  • Map.keySet() method provides Set of Keys

FindKeysFromValueInMap1.java

package in.bench.resources.find.map.keys;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class FindKeysFromValueInMap1 {

	// main() method
	public static void main(String[] args) {

		// variable
		String value = "India";


		// 1. HashMap
		Map<Integer, String> map = new HashMap<>();


		// 1.1 Add entries
		map.put(1, "India");
		map.put(2, "America");
		map.put(null, "India");
		map.put(3, "Britain");
		map.put(4, null);
		map.put(5, "India");


		// 1.2 print original/actual Map entries
		System.out.println("Original/actual Map entries :- \n" + map);


		// 2. invoke getKeysByValue() method
		Set<Integer> set = getKeysByValue(map, value);


		// 2.1 print to console
		System.out.print("\nKeys for Value '" + value + "' :- \n" + set);
	}


	/**
	 * This method returns Set of keys based on the passed Value
	 * 
	 * Map.keySet();
	 * 
	 * @param map
	 * @param value
	 * @return
	 */
	private static Set<Integer> getKeysByValue(Map<Integer, String> map, String value) {

		// store keys in Set
		Set<Integer> set = new HashSet<>();


		// keySet() - get Keys based on Value
		for(Integer key : map.keySet()) {

			// compare
			if(Objects.equals(map.get(key), value)) {

				// add to Set
				set.add(key);
			}
		}

		// return
		return set;
	}
}

Output:

Original/actual Map entries :- 
{null=India, 1=India, 2=America, 3=Britain, 4=null, 5=India}

Keys for Value 'India' :- 
[null, 1, 5]

2.2 Using entrySet() method of Map interface :

  • Map.entrySet() method provides Set of Map entries in the form of KeyValue pairs

FindKeysFromValueInMap2.java

package in.bench.resources.find.map.keys;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class FindKeysFromValueInMap2 {

	// main() method
	public static void main(String[] args) {

		// variable
		String value = "India";


		// 1. HashMap
		Map<Integer, String> map = new HashMap<>();


		// 1.1 Add entries
		map.put(1, "India");
		map.put(2, "America");
		map.put(null, "India");
		map.put(3, "Britain");
		map.put(4, null);
		map.put(5, "India");


		// 1.2 print original/actual Map entries
		System.out.println("Original/actual Map entries :- \n" + map);


		// 2. invoke getKeysByValue() method
		Set<Integer> set = getKeysByValue(map, value);


		// 2.1 print to console
		System.out.print("\nKeys for Value '" + value + "' :- \n" + set);
	}


	/**
	 * This method returns Set of Map Entries based on the passed Value
	 * 
	 * Map.entrySet();
	 * 
	 * @param map
	 * @param value
	 * @return
	 */
	private static Set<Integer> getKeysByValue(Map<Integer, String> map, String value) {

		// store keys in Set
		Set<Integer> set = new HashSet<>();


		// entrySet() - get Keys based on Value
		for(Map.Entry<Integer, String> entry : map.entrySet()) {

			// compare
			if(Objects.equals(entry.getValue(), value)) {

				// add to Set
				set.add(entry.getKey());
			}
		}

		// return
		return set;
	}
}

Output:

Original/actual Map entries :- 
{null=India, 1=India, 2=America, 3=Britain, 4=null, 5=India}

Keys for Value 'India' :- 
[null, 1, 5]

Q) How to make HashMap synchronized ?

Map map = Collections.synchronizedMap(hm);

In the following article, we will discuss same example using Java 8 Stream writing the same logic in an elegant way thus reducing boiler-plate code

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java – How to convert ArrayList to LinkedList ?
Java 8 – How to check whether a number exists in an Arrays or List or Stream ?