Different ways to iterate TreeSet in Java

Using Iterator –

package treeset;

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

public class IteratingTreeSet {
	public static void main(String[] args) {
		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");
		Iterator<String> it = treeSetObj.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}

	}
}

Output is –

mohan
ram
rohan
sohan

Using for-each loop –

package treeset;

import java.util.Set;
import java.util.TreeSet;

public class IteratingTreeSetSecWay {
	public static void main(String[] args) {
		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");
		for (String str : treeSetObj) {
			System.out.println(str);
		}
	}
}

Output is –


mohan
ram
rohan
sohan

 


We can’t iterate TreeSet using Listiterator, Enumeration and normal for loop(as we don’t have get() method in TreeSet like ArrayList).