Example of the java.util.TreeSet class

The java.util.TreeSet of java  is similar to the class  HashSet except that it sorts the items in ascending order. The data is stored in a TreeMap which is a balanced binary tree or in a SorteMap.

The access time is very fast, which makes TreeSet a great choice when the data is large and needs to be found quickly.

The TreeSet implements 4 constructors:

- TreeSet(): creates an empty TreeSet.
- TreeSet(Collection c): creates a TreeSet which contains items from the object collection c.
- TreeSet(Comparator comp): creates a TreeSet empty that will be sorted according to the comparator.
- TreeSet(SortedSet sset): Creates a TreeSet that contains the elements of sset.

TreeSet methods

void add(Object o)
Uses the put() of TreeMap to add a pair.

void addAll(Collection c)
Adds a set of items to the list.

void remove(Object o)
Removes the first instance from the list.

void clear()
Deletes all elements.

SortedSet subSet(Object E1, Object E2)
Returns the sublist of elements that lie between two bounds [E1, E2].

SortedSet headSet(Object E)
Returns the set of elements that are strictly less than E.

SortedSet tailSet(Object E)
Returns the set of elements that are greater than or equal to E.

Object first()
Returns the first item in this ordered list (the smallest).

Object last()
Returns the last item in this ordered list (the largest).

Example

In this example, we'll test two types: String and Integer. TreeSet  is able to also sort strings according to its alphanumeric ASCII code.

import java.util.TreeSet; 

public class Main {
public static void main(String args[]) {
// TreeSet of type String
TreeSet tsetString = new TreeSet();

// add objects of type String
tsetString.add("D");
tsetString.add("G");
tsetString.add("Z");
tsetString.add("A");
tsetString.add("F");
tsetString.add("T");
tsetString.add("S");
tsetString.add("M");

//Display
System.out.println(tsetString);

// TreeSet of type Integer
TreeSet tsetInteger = new TreeSet();

// add objects of type Integer
tsetInteger.add(5);
tsetInteger.add(87);
tsetInteger.add(42);
tsetInteger.add(24);
tsetInteger.add(23);
tsetInteger.add(152);
tsetInteger.add(70);
tsetInteger.add(54);
System.out.println(tsetInteger);
}
}
Output:

[A, D, F, G, M, S, T, Z]
[5, 23, 24, 42, 54, 70, 87, 152]
We can see here that both lists contain values sorted in order crescent.

You can check out these tutorials on the TreeSet object collection:

Browse TreeSet using Iterator
Add an element to TreeSet
Remove an element from TreeSet
Remove all elements from TreeSet
Difference between TreeSet and HashSet
Convert a HashSet to a TreeSet
Example of a TreeSet with Comparable
Sort TreeSet in descending order
Check if an element exists in TreeSet

References:
TutorialsPoint: java - The TreeSet class
Javadoc: TreeSet