How to Get All Keys From Map With a Value in Java


Suppose we want to get all keys from a hashmap that match a certain value in Java.

Let’s start with this hashmap.

Map<String, Integer> map = new HashMap<>();
map.put("corgi",    1);
map.put("pug",      2);
map.put("shih tzu", 3);
map.put("husky",    1);

1. Filtering with the Stream API (Java 8+)#

If we’re using JDK8+, we can use the Stream API to obtain all keys matching a certain value.

List<String> getKeysWithValue(Map<String, Integer> map, Integer value) {
  return map
    .entrySet()
    .stream()
    .filter(e -> Objects.equals(e.getValue(), value))
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());
}

We want to use Objects.equals() for comparisons here because hashmaps can contain null values.

2. Filtering with standard loops#

If we’re using JDK7, we can obtain the same functionality using standard for loops.

List<String> getKeysWithValue(Map<String, Integer> map, Integer value) {
  List<String> keys = new ArrayList<String>();
  for(String key : map.keySet()) {
    if(Objects.equals(map.get(key), value))
      keys.add(key);
  }
  return keys;
}