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 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); 
+6
source share
1 answer

You must use the Map::computeIfAbsent to create or retrieve a List :

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

Source: https://habr.com/ru/post/1014426/


All Articles