Maps

As already mentioned maps do not directly support streams. There’s no stream() method available on the Map interface itself, however you can create specialized streams upon the keys, values or entries of a map via map.keySet().stream(), map.values().stream() and map.entrySet().stream().

Furthermore maps support various new and useful methods for doing common tasks.

  1. Map<Integer, String> map = new HashMap<>();
  2. for (int i = 0; i < 10; i++) {
  3. map.putIfAbsent(i, "val" + i);
  4. }
  5. map.forEach((id, val) -> System.out.println(val));

The above code should be self-explaining: putIfAbsent prevents us from writing additional if null checks; forEach accepts a consumer to perform operations for each value of the map.

This example shows how to compute code on the map by utilizing functions:

  1. map.computeIfPresent(3, (num, val) -> val + num);
  2. map.get(3); // val33
  3. map.computeIfPresent(9, (num, val) -> null);
  4. map.containsKey(9); // false
  5. map.computeIfAbsent(23, num -> "val" + num);
  6. map.containsKey(23); // true
  7. map.computeIfAbsent(3, num -> "bam");
  8. map.get(3); // val33

Next, we learn how to remove entries for a given key, only if it’s currently mapped to a given value:

  1. map.remove(3, "val3");
  2. map.get(3); // val33
  3. map.remove(3, "val33");
  4. map.get(3); // null

Another helpful method:

  1. map.getOrDefault(42, "not found"); // not found

Merging entries of a map is quite easy:

  1. map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
  2. map.get(9); // val9
  3. map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
  4. map.get(9); // val9concat

Merge either put the key/value into the map if no entry for the key exists, or the merging function will be called to change the existing value.