Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last 25 elements of a SortedSet?

Tags:

java

sortedset

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 :-(
like image 654
Steve McLeod Avatar asked Feb 24 '09 13:02

Steve McLeod


People also ask

How do you find the last element in a sorted set?

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.

Is SortedSet ordered?

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.

What is the difference between SortedSet and NavigableSet?

SortedSet is an interface (it defines the functionality) and Treeset is an implementation. NavigableSet is also an interface subtype of the SortedSet.

Does SortedSet allow null values?

Yes, you can.


1 Answers

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() );
like image 183
Chris Kessel Avatar answered Oct 04 '22 10:10

Chris Kessel