View RSS Feed

My Java Tips

Using Treeset

Rate this Entry
by , 11-13-2011 at 12:29 PM (2061 Views)
TreeSet belongs to Java Collection Framework and is very rare situations. In this post, I will briefly discuss when to use TreeSet and how to use it.

To use it, you have to import java.util.TreeSet in your class. TreeSet is not synchronized so if a TreeSet is concurrently accessed by threads then thread modifying the contents must be synchronized externally. TreeSet provides following constructors:
TreeSet(Collection c)
TreeSet(Comparator c)
TreeSet(SortedSet s)

Since TreeSet is a type of Set, therefore duplicate values are not allowed. Also you cannot insert or fetch values from a particular index. Inserting and fetching value from an index is the property of Lists.

Ordering of elements in TreeSet is important. TreeSet maintains alphabetic order of elements in it.

Time for an example:

Java Code:
Vector vector = new Vector();

Iterator it = vector.iterator();

System.out.println("Vector: " +;

TreeSet ts = new TreeSet(vector);
it = ts.iterator();

System.out.println("TreeSet: " +;

Vector: String3
Vector: String1
Vector: String3
TreeSet: String1
TreeSet: String3

The output is very interesting. It shows that TreeSet ignored duplicate values. Also TreeSet has ordered the elements in ascending order.

It is true to say that TreeSet is slower than HashSet and there is no tuning parameter for TreeSet. But still, TreeSet is a good choice in scenarios where you need a set with natural order.

Submit "Using Treeset" to Facebook Submit "Using Treeset" to Digg Submit "Using Treeset" to Submit "Using Treeset" to StumbleUpon Submit "Using Treeset" to Google