如何从Java 8中的Iterator获取n个第一个值? [英] How to get n first values from an Iterator in Java 8?
问题描述
我使用 HashMap 进行了排序-java>对地图进行排序< Key,Value>通过值(Java),我有一个 LinkedHashMap
,即一个 Iterable
,它保证了迭代顺序。
I have sorted a HashMap
using Sort a Map<Key, Value> by values (Java) to that I have a LinkedHashMap
, i.e. an Iterable
which garantees iteration order.
现在,我想检索第一个 java.util.List
> n 带有单行的地图条目,如果可能的话,使用Java 8 Collection Stream API技术。
Now, I'd like to retrieve a java.util.List
of the first n
entries of the map with a one-liner, if possible with a Java 8 Collection Stream API-technique.
我发现如何从Iterator获取两个连续的值,这解释了有可能用数组来做,但这不优雅,不同于我打算获得 List
(虽然可以转换,但这是一个不必要的步骤)和需要一个额外的方法。
I found how can i get two consecutive values from Iterator which explains that there's a possibility to do that with an array, but that's not elegant, differs from my intention to get a List
(although that can be transformed, but it's an unnecessary step) and requires an extra method.
推荐答案
流 entrySet
并限制流
到第一个 n
元素:
Stream the entrySet
and limit the Stream
to the first n
elements:
List<Map.Entry<Key,Value>> firstN =
map.entrySet().stream().limit(n).collect(Collectors.toList());
这篇关于如何从Java 8中的Iterator获取n个第一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!