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)
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;
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");
}
We can use computeIfAbsent
to make it elegant:
map.computeIfAbsent("my_key", k -> new ArrayList<>());
map.get("my_key").add("new_str");
Top comments (0)