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:
1
2
3

SortedSet<Integer> setNumbers = new TreeSet<>(); setNumbers.addAll(Arrays.asList( 2 , 1 , 4 , 3 , 6 , 5 , 8 , 7 , 0 , 9 )); System.out.println( "Sorted Set: " + setNumbers); 
Output:
1

Sorted Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
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:
1
2
3
4
5
6
7
8
9
10
11
12
13

public interface SortedSet<E> extends Set<E> { // Rangeview SortedSet<E> subSet(E fromElement, E toElement); SortedSet<E> headSet(E toElement); SortedSet<E> tailSet(E fromElement); // Endpoints E first(); E last(); // Comparator access Comparator<? super E> comparator(); } 
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.
Endpoint operations:
 first(): returns the first (lowest) element currently in the set.
 last(): returns the last (highest) element currently in the set.
Comparator access:
 comparator(): returns the comparator used to order the elements in the set, or null if this set uses the natural ordering of its elements.
Leave a Reply