1. Understanding SortedSet
The key characteristic of a SortedSet is that, it sorts elements according to their natural ordering or by a specified comparator. So considering using a TreeSet when you want a collection that satisfies the following conditions:
- Duplicate elements are not allowed.
- Elements are sorted by their natural ordering (default) or by a specified comparator.
Here’s an example illustrates this characteristic of a SortedSet:
Here, we add elements of an array list to a TreeSet, and as you can see, the duplicate elements are removed and they are sorted by alphanumeric order (natural ordering of numbers).
In addition to basic collection operations and normal set operations, the SortedSet provides the following types of operations:
- Range view: extracts a portion of the set, i.e. a range.
- Endpoints: returns the first and the last element in the sorted set.
- Comparator access: returns the comparator, if an, used to sort the set.
Hence the following interface abstracts a SortedSet:
Let’s look at each type of operation in details. Range view operations:
- subSet(E fromElement, E toElement): returns a sorted set which is a portion of the set whose elements range from fromElement, inclusive, to toElement, exclusive.
- headSet(E toElement): returns a sorted set which is a portion of the set whose elements are strictly less than toElement.
- tailSet(E fromElement): returns a sorted set which is a portion of the set whose elements are greater than or equal to fromElement.
- first(): returns the first (lowest) element currently in the set.
- last(): returns the last (highest) element currently in the set.
- comparator(): returns the comparator used to order the elements in the set, or null if this set uses the natural ordering of its elements.