TreeSet is the SortedSet interface in Java that uses a Tree for storage. TreeSet applies the natural order of the elements. Here, In this post, we will see “how to create a TreeSet and how to iterates its data?”

Easiest representation of TreeSet in Java...!!! Share on X

Syntax:

Set<Integer> setOfIntegers = new TreeSet<>();

Note: In the above syntax sample, we are creating a TreeSet of type Integer.

Example

import java.util.Set;
import java.util.TreeSet;

public class TreeSetSample {

	public static void main(String[] args) {
		
        //Creating a TreeSet of Integer
		Set<Integer> setOfIntegers = new TreeSet<>();
		
		setOfIntegers.add(107);
		setOfIntegers.add(90);
		setOfIntegers.add(95);
		setOfIntegers.add(95);
		
		System.out.println("Iteration over Set of Integers:");
		for(int t : setOfIntegers){
		System.out.println(t);
		}
		
        //Creating a TreeSet of String
		Set<String> setOfStrings = new TreeSet<>();

		setOfStrings.add("Yogi");
		setOfStrings.add("Gaurangee");
		setOfStrings.add("Pulkit");
		setOfStrings.add("Yashika");
		setOfStrings.add("Yash");
        setOfStrings.add("Isha");
		setOfStrings.add("Deepak");

		System.out.println("Iteration over Set of Strings:");
		for(String t : setOfStrings){
			System.out.println(t);
		}
		
		
	}
}

 

Output:

Iteration over Set of Integers:
90
95
107
Iteration over Set of Strings:
Deepak
Gaurangee
Isha
Pulkit
Yash
Yashika
Yogi

 

Easiest representation of TreeSet in Java...!!! Share on X

 

If you like this post, please click like button and share it with others on Twitter. Also, check out my other useful blog posts on Java:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts