开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜