Tech and Media Labs
This site uses cookies to improve the user experience.




Java Collections - SortedSet

Jakob Jenkov
Last update: 2014-06-23

The java.util.SortedSet interface is a subtype of the java.util.Set interface. It behaves like a normal set with the exception that the elements are sorted internally. This means that when you iterate the elements of a SortedSet the elements are returned in the sorted order.

The order of the sorting is either the natural sorting order of the elements (if they implement java.lang.Comparable), or the order determined by a Comparator that you can give to the SortedSet.

By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method TreeSet.descendingIterator().

The Java Collections API only has one implementation of the SortedSet interface - the java.util.TreeSet class. The java.util.concurrent package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.

Here are two examples of how to create a SortedSet:

SortedSet setA = new TreeSet();

Comparator comparator = new MyComparator();
SortedSet setB = new TreeSet(comparator);

More Details in the JavaDoc

There is actually a lot more you can do with a TreeSet that is not part of the SortedSet interface, like getting the highest and lowest element, splitting the set into subsets based on two values etc. Check out the JavaDoc if you need any of these more special features.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC