Java 8 – How to get Keys from Value in HashMap using Stream ?

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

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 properties :

  • It is the implementation class of Map interface (i.e.; HashMap implements Map)
  • It stores in the form of KeyValue pairs using hashtable (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 using Stream :

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 using Stream :

  • Map.keySet() method provides Set of Keys
  • Map.keySet().stream() method provides stream of Map keys to iterate and apply multiple intermediate operations like filter, map, etc.
  • Finally collecting to a Set using terminal operation like collect passing Collectors.toSet() as methodargument

FindKeysFromValueInMap1UsingJava8.java

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

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class FindKeysFromValueInMap1UsingJava8 {

	// 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 using Java 8 Stream
	 * 
	 * Map.keySet();
	 * 
	 * @param map
	 * @param value
	 * @return
	 */
	private static Set<Integer> getKeysByValue(Map<Integer, String> map, String value) {

		// return Set of Keys
		return map
				.keySet()
				.stream()
				.filter(key -> Objects.equals(map.get(key), value))
				.map(key -> key)
				.collect(Collectors.toSet());
	}
}

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 using Stream :

  • Map.entrySet() method provides Set of Map entries in the form of KeyValue pairs
  • Map.entrySet().stream() method provides stream of Map entries to iterate and apply multiple intermediate operations like filter, map, etc.
  • Finally collecting to a Set using terminal operation like collect passing Collectors.toSet() as methodargument

FindKeysFromValueInMap2UsingJava8.java

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

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class FindKeysFromValueInMap2Using8 {

	// 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 using Java 8 Stream
	 * 
	 * Map.entrySet();
	 * 
	 * @param map
	 * @param value
	 * @return
	 */
	private static Set<Integer> getKeysByValue(Map<Integer, String> map, String value) {

		// return Set of Keys
		return map
				.entrySet()
				.stream()
				.filter(entry -> Objects.equals(entry.getValue(), value))
				.map(Map.Entry::getKey)
				.collect(Collectors.toSet());
	}
}

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 previous article, we already discussed about getting Keys passing Value in HashMap without using Java 8 Stream

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java 8 – How to convert String to ArrayList ?
Java 8 – How to Iterate over char[] Arrays ?