javalambdajava-8java-stream

Add value to List inside Map<String, List> in Java 8


Is there a better way in Java 8 to add a value to a List inside of a Map?

In java 7 i would write:

Map<String, List<Integer>> myMap = new HashMap<>();
...
if (!myMap.containsKey(MY_KEY)) {
    myMap.put(MY_KEY, new ArrayList<>());
}
myMap.get(MY_KEY).add(value);         

Solution

  • You should use the method Map::computeIfAbsent to create or get the List:

    myMap.computeIfAbsent(MY_KEY, k -> new ArrayList<>()).add(value);