Treeset overview

TreeSet is a java class which implements Set interface

Main features of TreeSet

It contains only unique elements, does not allow duplicates.

It stores elements in the sorted order

It does not maintain the insertion order, elements will be in sorted order.

It does not allow null value

We can create TreeSet using constructor as below

  1. TreeSet<String>  ts = new TreeSet<String>();
TreeSet<String>  ts = new TreeSet<String>();


  1. import java.util.*;
  2. public class TreeSetExample {
  3. public static void main(String args[]) {
  5. TreeSet<String> ts = new TreeSet<String>();
  7. ts.add("java");
  8. ts.add("c");
  9. ts.add("c++");
  11. //Displaying TreeSet elements
  12. System.out.println(ts);
  13. }
  14. }
import java.util.*;
public class TreeSetExample {
public static void main(String args[]) {

TreeSet<String> ts = new TreeSet<String>();


//Displaying TreeSet elements
Note : We can observe in the output that elements are in sorted order

When to use TreeSet ?

TreeSet should be used whenever we want to store only unique elements in a collection and we want to store them in the sorted order

When not use TreeSet ?

TreeSet should not be used whenever we need to allow duplicate elements and we need to maintain the insertion order within the collection

About the Author

Founder of
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to

Connect with me on Facebook for more updates

Share this article on