在 Java 8 中将值添加到 Map<String, List> 中的 List

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41861063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:12:23  来源:igfitidea点击:

Add value to List inside Map<String, List> in Java 8

javalambdajava-8java-stream

提问by tak3shi

Is there a better way in Java 8 to add a value to a List inside of a Map?

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

In java 7 i would write:

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

回答by Flown

You should use the method Map::computeIfAbsentto create or get the List:

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

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