【问题标题】:Add value to List inside Map<String, List> in Java 8 [duplicate]在 Java 8 中向 Map<String, List> 内的 List 添加值 [重复]
【发布时间】:2017-01-25 20:27:27
【问题描述】:

在 Java 8 中有没有更好的方法向 Map 内的 List 添加值?

在 java 7 中我会写:

Map<String, List<Integer>> myMap = new HashMap<>();
...
if (!myMap.containsKey(MY_KEY)) {
    myMap.put(MY_KEY, new ArrayList<>());
}
myMap.get(MY_KEY).add(value);         

【问题讨论】:

  • “更好”是什么意思?
  • @Andremoniy 看看下面的答案来理解“更好”。

标签: java lambda java-8 java-stream


【解决方案1】:

您应该使用Map::computeIfAbsent 方法来创建或获取List

myMap.computeIfAbsent(MY_KEY, k -> new ArrayList<>()).add(value);

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2023-03-26
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2017-01-28
    相关资源
    最近更新 更多