TreeSet Example in Java

TreeSet is a NavigableSet implementation based on a TreeMap. Sorting in the TreeSet makes it different from the HashSet. In TreeSet the elements are sorted ascending using their nartural sorting order. You can change the sorting by providing a Comparator while constructing a TreeSet.

TreeSet implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
Null is not allowed in a TreeSet unless you specify a comparator that can handle a Null.

TreeSet Example in Java


The elements get sorted naturally and you can see that in the output when we print the TreeSet

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn