Java 8 流 Map<K,V> 到 List<T>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21233183/
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 stream Map<K,V> to List<T>
提问by JamesCherrill
Given that I have some function that takes two parameters and returns one value , is it possible to convert a Map to a List in a Stream as a non-terminal operation? The nearest I cam find is to use forEach on the map to create instances and add them to a pre-defined List, then start a new Stream from that List. Or did I just miss something?
鉴于我有一些函数接受两个参数并返回一个值,是否可以将 Map 转换为 Stream 中的 List 作为非终端操作?最近我找到的是在地图上使用 forEach 来创建实例并将它们添加到预定义的列表中,然后从该列表开始一个新的流。还是我只是错过了什么?
Eg: The classic "find the 3 most frequently occurring words in some long list of words"
例如:经典的“在一些长单词列表中找到 3 个最常出现的单词”
wordList.stream().collect(groupingBy(Function.identity, Collectors.counting))).
(now I want to stream the entrySetof that map)
(现在我想流式传输该地图的 entrySet)
sorted((a,b) -> a.getValue().compareTo(b.getValue))).limit(3).forEach(print...
回答by Marko Topolnik
You should get the entrySet
of the map and glue the entries to the calls of your binary function:
您应该获取entrySet
映射并将条目粘贴到二进制函数的调用中:
inputMap.entrySet().stream().map(e->myFun(e.getKey(),e.getValue()));
The result of the above is a stream of T
instances.
上面的结果是一个T
实例流。
Update
更新
Your additional example confirms what was discussed in the comments below: group by
and sort
are by their nature terminal operations. They must be performed in fullto be able to produce even the first element of the output, so involving them as non-terminal operations doesn't buy anything in terms of performance/memory footprint.
您的附加示例证实了以下评论中讨论的内容:group by
并且sort
本质上是终端操作。他们必须进行完全能够产生均匀的输出的第一要素,所以涉及它们作为非终端操作不买在性能/内存占用方面的东西。
It happens that Java 8 defines sorted
as a non-terminal operation, however that decision could lead to deceptive code because the operation will block until it has received all upstream elements, and will have to retain them all while receiving.
碰巧 Java 8 定义sorted
为非终端操作,但是该决定可能导致欺骗性代码,因为该操作将阻塞,直到它接收到所有上游元素,并且在接收时必须保留它们。