Home > other >  Java - Merge Map containing list of string as values
Java - Merge Map containing list of string as values

Time:12-07

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;
          }
        );
        }

CodePudding user response:

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));
}
  • Related