Java 8流映射< K,V>列出< T> [英] Java 8 stream Map<K,V> to List<T>

查看:104
本文介绍了Java 8流映射< K,V>列出< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有一些函数需要两个参数并返回一个值,是否可以将Map转换为Stream中的List作为非终端操作?
最近的I cam找到的是在地图上使用forEach来创建实例并将它们添加到预定义的List中,然后从该List开始一个新的Stream。或者我错过了什么?

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?

例如:经典的在一些长词中找到3个最常出现的单词

Eg: The classic "find the 3 most frequently occurring words in some long list of words"

wordList.stream().collect(groupingBy(Function.identity, Collectors.counting))).

(现在我想流式传输该地图的entrySet)

(now I want to stream the entrySetof that map)

sorted((a,b) -> a.getValue().compareTo(b.getValue))).limit(3).forEach(print...


推荐答案

你应该得到 entrySet地图的并将条目粘贴到二进制函数的调用中:

You should get the entrySet of the map and glue the entries to the calls of your binary function:

inputMap.entrySet().stream().map(e->myFun(e.getKey(),e.getValue()));

以上结果是 T 个实例的流。

The result of the above is a stream of T instances.

您的其他示例确认了以下评论中讨论的内容: group by sort 是他们的本质终端操作。他们必须完整执行才能生成输出的第一个元素,所以将它们作为非终端操作参与不买在性能/内存占用方面的任何事情。

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 full to 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.

碰巧Java 8将 sorted 定义为非终端操作,但是该决定可能导致欺骗性代码,因为操作将阻塞,直到它收到所有上游元素,并且在接收时必须保留所有这些。

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流映射< K,V>列出< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆