Create treeset in java

Example

package com.w3schools;
 
import java.util.Iterator;
import java.util.TreeSet;
 
public class Test {	 
    public static void main(String[] args) {
    	//Create TreeSet object.
    	TreeSet<String> treeSet = new TreeSet<String>();
 
	//Add objects to the HashSet.
    	treeSet.add("Jai");
    	treeSet.add("Mahesh");
    	treeSet.add("Hemant");
	treeSet.add("Vishal");
	treeSet.add("Naren");
 
	//Print the TreeSet object.
	System.out.println("TreeSet elements:");
	System.out.println(treeSet);
 	//Print the TreeSet elements using iterator.
	Iterator<String> iterator=treeSet.iterator();
	System.out.println("TreeSet elements using iterator:");
	while(iterator.hasNext()){  
	   System.out.println(iterator.next());  
	}  
    }
}

Output

TreeSet elements:
[Hemant, Jai, Mahesh, Naren, Vishal]
TreeSet elements using iterator:
Hemant
Jai
Mahesh
Naren
Vishal