I have a sorted Map and want to return the first n elements.
public static Map getFirstEntries(final Map sortedMap, int elementsToReturn) {
elementsToReturn = (sortedMap.size() > elementsToReturn)
? elementsToReturn
: sortedMap.size();
return sortedMap.entrySet()
.stream()
.limit(elementsToReturn)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue)));
}
Looks like you solved at least some of your problem already. I'd suggest a couple refinements, though.
You probably want the parameter type to be SortedMap
so you don't accidentally pass in something like a plain HashMap
for which there is no defined order. You might want the return type to be a SortedMap
as well. To make this work, you have to use the four-arg overload of Collectors.toMap
, whose fourth arg is a supplier that lets you control the construction of the map. If you didn't do that, you'd get a plain HashMap
.
The third arg is the merge function, which is called when multiple values for the same key are merged. You know the keys are unique since you're getting them out of a map in the first place, so we needn't worry about this. I've just had this return the first value, but you could also have it throw an exception or something.
Finally, you don't need to check the size up front, since limit(n)
will work fine if n
is greater than the number of entries passed through.
The revised code would be as follows:
public static <K,V> SortedMap<K,V> getFirstEntries(SortedMap<K,V> sortedMap, int elementsToReturn) {
return sortedMap.entrySet()
.stream()
.limit(elementsToReturn)
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue,
(v1,v2) -> v1, TreeMap::new));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With