How to add an element to HashMap<K, List<V>> using merge function

Viewed 364

When maintaining a HashMap, merge is a very useful command. I like the concise way to add a number to a sum using expressions like map.merge(key, value, Double::sum);

I have a HashMap<String, List> that I want to update. I could use something like

if (!map.containsKey(key)) map.put(key, new List());
map.get(key).add(value);

is there a more elegant way using merge to achieve this?

2 Answers

The merge method can be similarly used here:

map.merge(key,
     List.of(value),
     (l1, l2) -> Stream.concat(l1.stream(), Stream.of(value)).collect(Collectors.toList()));

Note: I used Stream here because the list can be immutable (this is the case with the initial value List.of(value))

Unless you're using a ConcurrentHashMap, however, I doubt this would be as elegant as the simple if solution.

If you have all of the data you need to build the Map up-front then you can do this

final Map<String, List<X>> result = list.stream().collect(Collectors.groupingBy(x -> x.key, Collectors.toList()));

Otherwise, you could use computeIfAbsent, but it's basically the same as what you've already got

result.computeIfAbsent(x.key, (key) -> new ArrayList<>()).add(x);
Related