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 Key–Value 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 upper–limit
- 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,
- Using keySet() method of Map interface using Stream
- Using entrySet() method of Map interface using Stream
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 method–argument
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 Key–Value 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 method–argument
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 ?
- HashMap can be easily converted into synchronized HashMap
- Using utility method synchronizedMap(hm); of java.util.Collections class
- Read Java – How to get synchronized version of Collection ? for more details
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 :
- Java 8 – Filter null and empty values from a Stream
- Java 8 – Filter a Map by its Key and Value
- Java 8 – How to store multiple values for single key in HashMap and Filter them ?
- Java 8 – How to get Keys from Value in HashMap using Stream ?
References :
- https://www.benchresources.net/hashmap-class-in-java/
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
- https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html
Happy Coding !!
Happy Learning !!