Java 8 Map Merge Method

I am trying to create a HashMap that will contain an integer as a key and a list of strings as a value:

Map<Integer, List<String>> map = new HashMap<Integer, List<String>>(30); 

I want to fill it out efficiently somehow. I went:

 map.merge(search_key, new ArrayList<>(Arrays.asList(new_string)), (v1, v2) -> { v1.addAll(v2); return v1; }); 

This code is small and elegant, but the problem is that I create a new List in every call. Is there a way that I can skip list creation after the first merge and just add new_string to the first list created?

+6
source share
1 answer

You should use the Map :: computeIfAbsent method to create a list lazily:

 map.computeIfAbsent(search_key, k -> new ArrayList<>()) .add(new_string); 
+16
source

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


All Articles