Java – Iterate through TreeSet in 3 ways

In this article, we will discuss various ways to iterate through TreeSet – 3 ways

Various ways to iterate through TreeSet:

  1. Enhanced for-loop introduced in Java 1.5 version
  2. Iterating using Iterator of Collection interface
  3. forEach() loop introduced in Java 1.8 version

DifferentWaysToIterateTreeSet.java

package in.bench.resources.collection;

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

public class DifferentWaysToIterateTreeSet {

	public static void main(String[] args) {

		// creating TreeSet object of type String
		TreeSet<String> tset = new TreeSet<String>();

		// adding elements to TreeSet object
		tset.add("Samsung");
		tset.add("iPhone");
		tset.add("OnePlus");
		tset.add("Motorola");
		tset.add("iPhone"); // duplicate object
		tset.add("Micromax");

		// Way 1: Iterating using enhanced for-loop in Java 1.5
		System.out.println("Way 1: Iterating using"
				+ " enhanced for-loop in Java 1.5 version\n");
		for(String str : tset) {
			System.out.println(str);
		}

		// Way 2: Iterating using Iterator of Collection interface
		System.out.println("\n\nWay 2: Iterating using"
				+ " Iterator of Collection interface\n");
		Iterator<String> itr = tset.iterator();
		while(itr.hasNext()) {
			System.out.println(itr.next());
		}

		// Way 3: Iterating using forEach loop in Java 1.8 version
		System.out.println("\n\nWay 3: Iterating using"
				+ " forEach loop in Java 1.8\n");
		tset.forEach(fone -> System.out.println(fone));
	}
}

Output:

Way 1: Iterating using enhanced for-loop in Java 1.5 version

Micromax
Motorola
OnePlus
Samsung
iPhone

Way 2: Iterating using Iterator of Collection interface

Micromax
Motorola
OnePlus
Samsung
iPhone

Way 3: Iterating using forEach loop in Java 1.8

Micromax
Motorola
OnePlus
Samsung
iPhone

From above example, TreeSet

  • doesn’t allow duplicate elements
  • while iterating, retrieves element in natural sorting-order for String type
  • maximum of one null object is allowed till Java 1.6 version
  • Starting Java 1.7 version, even one null object isn’t allowed
  • Throws java.lang.NullPointerException for null object added to TreeSet, if you are using JDK version greater than 1.6

References:

Happy Coding !!
Happy Learning !!

Java - 5 ways to iterate through TreeMap
Java - Iterate through LinkedList in 5 ways