Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 somehow populate it efficiently. What I came up was:

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

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

like image 899
Anastasios Andronidis Avatar asked Jun 19 '14 11:06

Anastasios Andronidis


1 Answers

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

map.computeIfAbsent(search_key, k -> new ArrayList<>())
   .add(new_string);
like image 60
nosid Avatar answered Oct 02 '22 13:10

nosid