开发者

Java - Merge Map containing list of string as values

开发者 https://www.devze.com 2022-12-07 21:08 出处:网络
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?

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

精彩评论

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

关注公众号