I have sorted a HashMap using Sort a Map 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.
解决方案
Stream the entrySet and limit the Stream to the first n elements:
List> firstN =
map.entrySet().stream().limit(n).collect(Collectors.toList());