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?
You should use the method Map::computeIfAbsent to create a list lazily:
map.computeIfAbsent(search_key, k -> new ArrayList<>())
.add(new_string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With