CodesJava

Easy learning with example program codes

how to iterate 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.

We can use iterator interface. It is a universal iterator as we can apply it to any Collection object. It provides the functionality of read and remove operations. Collection interface provides iterator() method to get the Iterator object. Iterator interface have following to methods to iterate collection objects.

hasNext(): It returns true if the iteration has more elements.
next(): It returns the next element in the iteration.

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


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap