Java SortedSet Interface

Category: Java   Tags: Java, Java Collection, Java Set Interface, Java SortedSet Interface

The SortedSet interface extends Set and keep the elements in ascending order. Elements are sorted according to natural ordering or according to a Comparator provided at the time of its creation. SortedSet is a generic interface:

                          interface SortedSet<E>
                                

Here, E specifies the type of objects that the set will contain.

Methods

In addition to the methods defined by Set, SortedSet defines some of its own:

E first()
Returns the first element of this set.
E last()
Returns the last element of this set.
Comparator<? super E> comparator()
Returns the Comparator used to order the element of this set. If this set uses natural ordering, null will be returned.
subSet(E fromElement, E toElement)
Returns a subset of this set whose elements range from fromElement(inclusive) to toElement(exclusive). Changes in the returned set are reflected in this set, and vice-versa.
SortedSet<E> tailSet(E element)
Returns a subset of this set whose elements are greater than or equal to element. Changes in the returned set are reflected in this set, and vice-versa.
SortedSet<E> headSet(E element)
Returns a subset of this set whose elements are less than element. Changes in the returned set are reflected in this set, and vice-versa.

TreeSet is a commonly used class that implement SortedSet interface.