Java 8 | HashMap 的并行流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36990108/
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
Java 8 | Parallel Stream for a HashMap
提问by John S.
In java 8 I know that they added the parallel stream which takes advantage of multicore processors, and I know that you can use it with something like this:
在 java 8 中,我知道他们添加了利用多核处理器的并行流,并且我知道您可以将它用于以下内容:
List<String> list = new ArrayList<String>();
list.parallelStream().forEach(str -> System.out.println(str));
But how would I achieve something like this with a HashMap?
但是我将如何使用 HashMap 实现这样的目标?
Map<String, Integer> map = new HashMap<String, Integer>();
// won't work, because the Map class doesn't have the .parallelStream()
map.parallelStream().forEach((str, num) -> System.out.println(str + ":" + num));
Does anyone know how to do something like this? Thanks
有谁知道如何做这样的事情?谢谢
回答by rgettman
You can't stream a Map
directly, but you can stream its entry set, given with the entrySet()
method. Extract the key and value from the entry object.
您不能Map
直接流式传输 a ,但可以流式传输其条目集,由entrySet()
方法给出。从条目对象中提取键和值。
map.entrySet()
.parallelStream()
.forEach(entry -> System.out.println(entry.getKey() + ":" + entry.getValue()));
回答by AJ Jwair
You can get the 'entry set' from the hash map by calling map.entrySet(), you can call parallelStream() on the returned entry set.
您可以通过调用 map.entrySet() 从哈希映射中获取“条目集”,您可以在返回的条目集上调用 parallelStream()。
Please note that the returned object is a set of Map.Entry. You can get the key and value from an entry set item by calling getKey() and getValue() on it respectively. As follows:
请注意,返回的对象是一组 Map.Entry。您可以通过分别调用 getKey() 和 getValue() 来从条目集项目中获取键和值。如下:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.entrySet().parallelStream().forEach((e) -> System.out.println(e.getKey() + ":" + e.getValue()));