Java - Merge Map containing list of string as values
I have a Map
below which I am merging to update the map containing List. Is there a better / concise way of performing this merge operation?
Map<String, List<String>> myMap = new HashMap<>();
List<String> keys = externalService.getKeys();
for(String key: keys){
List<String> value = externalService.get(key);
myMap.merge(
key,
value,
(existingValue, newValue) -> {
existingValue.addAll(newValue);
return existingValue;
}
);
开发者_开发问答 }
You can use computeIfAbsent()
if you're willing to allocate the extra list for new keys:
for (String key : keys) {
myMap.computeIfAbsent(key, k -> new ArrayList<>())
.addAll(externalService.get(key));
}
精彩评论