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


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

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