Is there a Java equivalent of Python's defaultdict?

Viewed 15506

In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,

from collections import defaultdict
d = defaultdict(list)
d[1].append(2)
d[1].append(3)
# d is now {1: [2, 3]}

Is there an equivalent to this in Java?

8 Answers

In Java 8+ you can use:

map.computeIfAbsent(1, k -> new ArrayList<Integer>()).add(2);
Related