TreeSet class in Java
Set is a collection that cannot contain duplicate elements.
TreeSet class is a NavigableSet implementation based on a TreeMap. It stores its elements in a red-black tree, which is a self-balancing binary search tree.
TreeSet is substantially slower than HashSet, but the elements are ordered based on their value.
TreeSet differs from HashSet in that it orders its elements in ascending order. That is, regardless of the insertion order of the elements, all elements are ordered in ascending order (their natural ordering to be precise).
TreeSet class doesn’t allow the null
element.
Java provides the TreeSet class as part of the Java Collections Framework. For an overview of the Java Collections Framework, check out my post Overview of the Java Collections Framework.
The following example illustrates the TreeSet class.
Example
Output
As you can see from the above output, there are no duplicate elements in the TreeSet. Also, TreeSet ordered the elements in their ascending order.
The above program showed the use of some of the common methods of the TreeSet class. For a complete list of all the available methods, refer the official docs.
Now since you know how to use the TreeSet class, check out other implementations of the Set interface: