Java SE API
Map.computeIfAbsent
Compute for missing or null mappings. A null result creates no new mapping. Do not structurally modify the map in the callback.
Formal Syntax & Structure
java syntaxjava
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| key | K | Target key. |
| mappingFunction | Function<? super K, ? extends V> | Produces a value for the key. |
Return Value
V
Existing or computed value, possibly null.
Working Example
Example Snippetjava
import java.util.*;public class Main {
public static void main(String[] args) { Map<String, List<String>> groups = new LinkedHashMap<>(); groups.computeIfAbsent("desk", key -> new ArrayList<>()).add("pen"); groups.computeIfAbsent("shelf", key -> new ArrayList<>()).add("book"); groups.computeIfAbsent("desk", key -> new ArrayList<>()).add("pad"); System.out.println(groups); Iterator<String> keys = groups.keySet().iterator(); while (keys.hasNext()) { if (keys.next().equals("shelf")) keys.remove(); } System.out.println(groups); }}