How to Iterate Over Elements of Java TreeSet


This example will tell us how to iterate through elements of a TreeSet object in Java.

Source Code

package com.beginner.examples;

import java.util.Iterator;
import java.util.TreeSet;

public class IterateThroughElementsOfTreeSet {

	public static void main(String[] args) {
		
	    //create TreeSet.
	    TreeSet treeSet = new TreeSet();
	   
	    treeSet.add("A");
	    treeSet.add("B");
	    treeSet.add("C");
	    treeSet.add("D");
	    
	    //use the method iterator() to get the Iterator.
	    Iterator iterator = treeSet.iterator();
	    
	    System.out.println("TreeSet contains : ");
	    while(iterator.hasNext()) {
	    	System.out.println(iterator.next());
	    }
	      
	}

}

Output:

TreeSet contains : 
A
B
C
D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments