如何从Java 8中的Iterator获取n个第一个值? [英] How to get n first values from an Iterator in Java 8?

查看:719
本文介绍了如何从Java 8中的Iterator获取n个第一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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屋!

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