java - Return first n elements from a Map using lambdas -


I have a sorted map and have to return the n elements first. Public static map getFirstEntries (last map sorted map, intint altonatorum) {elementsToReturn = (sortedMap.size ()> Reuters for elements)? Element Totron: Sorted map.size (); Return sorted map.entrySet () .stream () .limit (elementsToReturn) .collect (collectors.Toapap (map. Entry :: getKey, map.Entry :: getValue))); }

It seems that you have solved at least some of your problems. Suggest some improvements, though

You probably want to be the parameter type SortedMap , so that you can accidentally get a plain HashMap for which there is no scheduled order that you return The type should also be in the form of a sorted map . To make this work, you have to collectors. To use the four-azig surcharge of the map, whose fourth ARG is a supplier that lets you control the construction of the map. If you do not do this, you get a plain Hashem .

The third ARG merge function, which is called when multiple values ​​are merged for the same key. You know that the keys are unique because you are meeting them in the first place, so we do not need to worry about it. I have just withdrawn the first value on this, but you can throw exceptions or something to it.

Finally, you do not need to check the size front, because the limit (

) the modified code will be as follows:

  Public stable & lt; K, V & gt; SortedMap & LT; K, V & gt; GetFirstEntries (sortedmap & lt; K, V & gt; sorted map, int element filename) {back sortedmap. antisat (). (Elementstoreitan) .collect (toMap (Map.Entry :: getKey, Map.Entry :: getValue, (v1, V2) -> v1, treemark :: new));}    

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -