Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Map.computeIfAbsent()

Returns the value for a key, creating it with a function if the key is absent.

Available since: Java 8

Syntax

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

Parameters

ParameterTypeDescription
keyKThe key.
mappingFunctionFunction<? super K, ? extends V>Creates a value from the key; called only when the key is absent.

Return value

VThe current (existing or newly created) value.

Examples

Grouping words by the first letter:

void main() {
    Map<Character, List<String>> byLetter = new TreeMap<>();
    for (String w : List.of("apple", "bean", "avocado", "beet", "corn")) {
        byLetter.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
    }
    IO.println(byLetter);
}

Output:

{a=[apple, avocado], b=[bean, beet], c=[corn]}

A simple cache: the function runs once per key:

void main() {
    Map<Integer, Long> cache = new HashMap<>();
    Function<Integer, Long> slowSquare = n -> {
        IO.println("computing " + n);
        return (long) n * n;
    };
    IO.println(cache.computeIfAbsent(12, slowSquare));
    IO.println(cache.computeIfAbsent(12, slowSquare));
}

Output:

computing 12
144
144

Notes

The main use is a map of lists: map.computeIfAbsent(key, k -> new ArrayList<>()).add(value). If the function returns null, no pair is added. The function must not modify the same map. Related methods: computeIfPresent() and compute().

See also

Related recipes

In the tutorial

  • Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.

Thanks for reading!

Donate to the site — we work hard for you.