CodesJava

Easy learning with example program codes

how to create a treeset in java


TreeSet

TreeSet extends AbstractSet and implements the NavigableSet interface. It maintains ascending order for its elements i.e. elements will be in sorted form.

Example

package com.codesjava;
 
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
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki