Java – Iterate through HashSet in 3 ways

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

Different ways to iterate through HashSet:

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

DifferentWaysToIterateHashSet.java

package in.bench.resources.java.collections;

import java.util.HashSet;
import java.util.Iterator;

public class DifferentWaysToIterateHashSet {

	public static void main(String[] args) {

		// creating HashSet object of type String
		HashSet<String> hset = new HashSet<String>();

		// adding elements to HashSet object
		hset.add("Sundar Pichai");
		hset.add("Satya Nadella");
		hset.add("Shiv Nadar");
		hset.add("Shantanu Narayen");
		hset.add("Sundar Pichai"); // duplicate object
		hset.add("Francisco D’Souza");

		// Way 1: Iterating using enhanced for-loop
		System.out.println("Way 1: Iterating using "
				+ "enhanced for-loop\n");
		for(String str : hset) {
			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&lt;String&gt; itr = hset.iterator();
		while(itr.hasNext()) {
			System.out.println(itr.next());
		}
	}
}

Output:

Way 1: Iterating using enhanced for-loop

Sundar Pichai
Shantanu Narayen
Shiv Nadar
Francisco D’Souza
Satya Nadella

Way 2: Iterating using Iterator of Collection interface

Sundar Pichai
Shantanu Narayen
Shiv Nadar
Francisco D’Souza
Satya Nadella

From above example, HashSet

  • doesn’t allow duplicate elements
  • maximum of one null object is allowed
  • while iterating, retrieve elements in random order

In the next article, we will see a demo example on how to iterate Set using Stream in Java 1.8 i.e.;

Related Articles:

To conclude, now there are 3 ways to iterate Set

References:

Happy Coding !!
Happy Learning !!

Java 8 - Iterating Set using forEach() method
Java - Adding one HashSet to another HashSet using addAll() method