Mutable version of Map.merge

Viewed 74

Java 8 has introduced some nice methods to the Map interface. To me, a gap is that there is no mutable version of the merge method.

For example, suppose map is a Map<String, List<Integer>> and you want to do this:

List<Integer> list = map.get("a");
if (list == null)
    list = map.put("a", new ArrayList<>());
list.add(1);

(I am aware that you can use Guava's MultiMap for this kind of thing, but I am interested in standard Java.)

To me, it feels like there ought to be a nice way of simplifying this in Java 8, but I can't find it. I reckon it should be a single method call, like

map.mutableMerge("a", 1, ArrayList::new, List::add);     // Not real code

but the best I could come up with using the new methods is

map.computeIfAbsent("a", k -> new ArrayList<>());
map.compute("a", (k, v) -> {
    v.add(1);
    return v;
});

but this is no better than the original. Am I missing something obvious?

1 Answers
Related