Java TreeSet is a Set implementation based on the TreeMap. Unlike HashMap, the elements of the TreeSet are ordered using their natural ordering. Also, unlike the Map implementations like TreeMap or HashMap, TreeSet does not maintain key value pairs but offers uniqueness of its elements.

If you do not want to sort the TreeSet elements using their natural ordering, you can provide custom Comparator when you crate the TreeSet object using below constructor.

public TreeSet(Comparator comparator)

The TreeSet class provides log(n) time cost for the add, remove and contains operations.

The TreeSet implementation is not synchronized. That means if multiple threads are trying to modify the TreeSet object at the same time then the access must be synchronized explicitly. If this is the case, you can either synchronize the TreeSet object or you can get the synchronized SortedSet object from the existing TreeSet using synchronizedSortedSet method of the Collections class like given below.

SortedSet sortedSet = Collections.synchronizedSortedSet(existingTreeSetObject);

The Iterator object obtained by the iterator method of the TreeSet is fail-fast. That means if the TreeSet object is structurally modified after obtaining the iterator (except by using iterator’s own remove method), calling any methods of the iterator object will throw ConcurrentModificationException.

Below given are some of the Java TreeSet examples which shows how to use TreeSet in Java.

Java TreeSet Examples