In Java I have a SortedSet that may have 100,000 elements. I would like to efficiently and elegantly get the last 25 elements. I'm a bit puzzled.
To get the first 25 I'd iterate and stop after 25 elements. But I don't know how to iterate in reverse order. Any ideas?
SortedSet<Integer> summaries = getSortedSet();
// what goes here :-(
The last() method of SortedSet interface in Java is used to return the last i.e., the highest element currently in this set. Where, E is the type of element maintained by this Set. Parameters: This function does not accepts any parameter. Return Value: It returns the last or the highest element currently in the set.
Interface SortedSet<E> A Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time. The set's iterator will traverse the set in ascending element order.
SortedSet is an interface (it defines the functionality) and Treeset is an implementation. NavigableSet is also an interface subtype of the SortedSet.
Yes, you can.
Throw the Set into a List and use subList(). I'm not sure how performant it is to create the List, so you'd have to run some tests. It'd certainly make the coding easy though.
List f = new ArrayList( summaries);
List lastTwentyFive = f.subList( summaries.size() - 25, summaries.size() );
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