10

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?

2
  • 1
    “This code is small and elegant” but broken. Trying to invoke addAll on the result of Arrays.asList won’t work…
    – Holger
    Jun 19, 2014 at 15:40
  • @Holger You are right. My mistake is that Arrays.asList(new_string) gives a fixed list, I will fix it. Jun 20, 2014 at 9:00

1 Answer 1

21

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.