Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
TreeSet in Java - Testingpool

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 […]