How to get n first values from an Iterator in Java 8?

主宰稳场 提交于 2019-12-22 08:24:03

问题


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.

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.

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.


回答1:


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());



回答2:


Writing more concise code with StreamEx:

List<Map.Entry<Key,Value>> firstN = EntryStream.of(map).limit(n).toList();


来源:https://stackoverflow.com/questions/44135683/how-to-get-n-first-values-from-an-iterator-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!