TreeSet in Java

In the previous post, we have learnt about LinkedHashSet. In this post, we will learn about TreeSet in java.

TreeSet has the following features.

  • Contains unique elements like HashSet.
  • The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
  • Important point to note is that it sorts the elements in ascending order.
  • It is non-synchronized.

However, it can be synchronized explicitly as given below.

SortedSet s = Collections.synchronizedSortedSet(new TreeSet(elements..));

 Example:

Let’s understand this with 2 examples i.e. with String and Integer.

Create TreeSet of String type:

import java.util.TreeSet;

public class TreeSetExample {

	public static void main(String[] args) {
		
		TreeSet<String> lSet = new TreeSet<String>();
		lSet.add("Apple");
		lSet.add("Mango");
		lSet.add("Banana");
		lSet.add("Orange");
		lSet.add("Date");
		lSet.add("Papaya");
		
		//Display the TreeSet
		System.out.println("TreeSet : "+lSet); // sorts elements in ascending order
	}
}

Output:

TreeSet : [Apple, Banana, Date, Mango, Orange, Papaya]

Example of TreeSet with Integer:

import java.util.TreeSet;

public class TreeSetExample {

	public static void main(String[] args) {
		
		TreeSet<Integer> lSet = new TreeSet<Integer>();
		lSet.add(35);
		lSet.add(25);
		lSet.add(45);
		lSet.add(15);
		lSet.add(5);
		lSet.add(55);
		
		//Display the TreeSet
		System.out.println("TreeSet : "+lSet); // sorts elements in ascending order
	}
}

Output:

TreeSet : [5, 15, 25, 35, 45, 55]


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

1 Response

  1. September 22, 2015

    […] the Previous post, we have learnt about TreeSet in java. In this post, we will learn HashMap in […]