DEV Community

Clark Ngo
Clark Ngo

Posted on

Why use Java - Map.computeIfAbsent

Follow Me, Shout Out, or Give Thanks!

Please πŸ’– this article. a small thing to keep me motivated =)
Twitter: @djjasonclark
Linkedin: in/clarkngo

computeIfAbsent

When to use?

  • if we want to do call a function if key is not found
  • good for initializing a data structure and inserting to map
  • a shorter implementation instead of doing on your own
default V computeIfAbsent(K key,
                          Function<? super K,? extends V> mappingFunction)
Enter fullscreen mode Exit fullscreen mode

Java docs - computeIfAbsent

It means, we can compute (call) a function, if key is absent (not found).

Scenario: I need a map that have this structure:

Map<String, List<String> map;
Enter fullscreen mode Exit fullscreen mode

So whenever we want to add a new key and a value, we usually do this:

if (map.get("my_key") == null) {
    map.get("my_key").add("new_str");
} else {
    // or Arrays.asList("new_str"),
    map.put("my_key", new ArrayList<>());
    map.get("my_key").add("new_str");
}
Enter fullscreen mode Exit fullscreen mode

We can use computeIfAbsent to make it elegant:

map.computeIfAbsent("my_key", k -> new ArrayList<>());
map.get("my_key").add("new_str");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)