How to Iterate Through HashSet elements in Java


In following example, we will learn how to iterate through elements HashSet object in Java.

Source Code

package com.beginner.examples;

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

public class IterateHashSetExample {

	public static void main(String[] args) {

		// Create a HashSet object
		HashSet hSet = new HashSet();

		// Add elements
		hSet.add("A");
		hSet.add("B");
		hSet.add("C");
		hSet.add("D");
		
		//Get an iterator for this collection
		Iterator iterator = hSet.iterator();
		
		System.out.println("All the elements:");
		//Iterate through the iterator
		while(iterator.hasNext())
		{
			String element = iterator.next();
			System.out.print(element+"t");
		}

	}

}

Output:

All the elements:
D	A	B	C

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments