Java – Get keys from value HashMap
This article shows a few ways to get keys from value in HashMap.
- 1. HashMap can contain null for key and value
- 2. Get all keys from HashMap – keySet()
- 3. Get keys from value in HashMap
- 4. Get keys from value in HashMap (Java 8 Stream)
- 5. HashMap only has one item
- 6. References
1. HashMap can contain null for key and value
When we create a method to find keys from value in HashMap
, we have to take care of the following concerns:
HashMap
can containnull
for key and value.HashMap
keys are unique, which means no duplication.HashMap
does not guarantee the insert order.- Single or multiple keys match to a single value.
A HashMap
example.
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
map.put("key4", 3);
map.put("key5", null); // null for value
map.put(null, 3); // null for key
2. Get all keys from HashMap – keySet()
The map.keySet()
returns a Set
, and the HashMap
does not guarantee the insert order.
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
map.put("key4", 3);
map.put("key5", null);
map.put(null, 3);
//Set<String> keys = map.keySet();
// print all keys
for (String key : map.keySet()) {
System.out.println(key);
}
Output
key1
null
key2
key5
key3
key4
3. Get keys from value in HashMap
To find all the keys that map to a certain value, we can loop the entrySet()
and Objects.equals
to compare the value and get the key.
Note
The common mistake is use the entry.getValue().equals(value)
to compare the value, because if the HashMap
contains a null
value, the method will throw a popular NullPointerException
.
3.1 Find all keys that containing the value of 3
.
package com.mkyong.basic;
import java.util.*;
public class FindKeysFromMap {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
map.put("key4", 3);
map.put("key5", null);
map.put(null, 3);
for (String key : getKeys(map, 3)) {
System.out.println(key);
}
}
private static Set<String> getKeys(Map<String, Integer> map, Integer value) {
Set<String> result = new HashSet<>();
if (map.containsValue(value)) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (Objects.equals(entry.getValue(), value)) {
result.add(entry.getKey());
}
// we can't compare like this, null will throws exception
/*(if (entry.getValue().equals(value)) {
result.add(entry.getKey());
}*/
}
}
return result;
}
}
Output
null
key3
key4
3.2 Find all keys that containing the value of null
.
for (String key : getKeys(map, null)) {
System.out.println(key);
}
Output
key5
4. Get keys from value in HashMap (Java 8 Stream)
4.1 Below is an equivalent example in Java 8.
package com.mkyong.basic;
import java.util.*;
import java.util.stream.Collectors;
public class FindKeysFromMapJava8 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
map.put("key4", 3);
map.put("key5", null);
map.put(null, 3);
for (String key : getKeysJava8(map, 3)) {
System.out.println(key);
}
}
/*private static Set<String> getKeys(Map<String, Integer> map, Integer value) {
Set<String> result = new HashSet<>();
if (map.containsValue(value)) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (Objects.equals(entry.getValue(), value)) {
result.add(entry.getKey());
}
}
}
return result;
}*/
private static Set<String> getKeysJava8(
Map<String, Integer> map, Integer value) {
return map
.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
}
Output
null
key3
key4
4.2 If we want to find only the first key that match the value.
private static Optional<String> getKeysJava8(
Map<String, Integer> map, Integer value) {
return map
.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.findFirst();
}
4.3 Or if we want a List
and Optional
.
private static Optional<List<String>> getKeysJava8Optional(
Map<String, Integer> map, Integer value) {
List<String> collect = map
.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
return Optional.of(collect);
5. HashMap only has one item
5.1 If the HashMap
only has one item, we can use map.keySet().toArray()
to convert the Set
to an Array
and [0]
to get the first item from the array, which means the first key from the HashMap
.
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
// the first key
Object key = map.keySet().toArray()[0];
System.out.println(key);
Output
key1
5.2 Can we use map.keySet().toArray()[5]
to get the sixth key from a HashMap
? The answer is a NO because the result will be a random key, HashMap
does not guarantee the insert order.
Do not try this
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
map.put("key4", 3);
map.put("key5", null);
map.put(null, 3);
Object key = map.keySet().toArray()[5]; // we expect the sixth key from a HashMap
System.out.println(key); // but the result is a random keys
Note
The HashMap
does not guarantee the insert order, this map.keySet().toArray()[0]
only works for HashMap
only has one item.