Iterate/loop elements/string objects of HashSet collection in java8 (example)

  1. HashSet class implements the Set interface, backed by a hash table.
  2. HashSet contains the unique elements.
    • HashSet does not contains any duplicate keys
    • HashSet can have only 1 null key.
  3. HashSet does not maintained the order of elements or keys.
  4. HashSet is UnSynchronized and not thread safe.
  5. Given a HashSet collection having String objects in java.
    • We would like to iterate or loop through HashSet collection using java 8.

1. Methods to traverse or loop HashSet collection in java.

  1. Traverse HashSet<String> using Iterator.
  2. Iterate HashSet<String> using Java 8 forEach.

2. Iterate or loop String objects of HashSet collection (java8/example)

package org.learn.collection.set.hset;

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

public class DemoIterationHashSet {

	public static void main(String[] args) {
		Set<String> setSports = new HashSet<>();
		setSports.add("Tennis");
		setSports.add("Cricket");
		setSports.add("Tennis");
		setSports.add(null);
		setSports.add("Basketball");
		setSports.add("Cricket");
		setSports.add(null);
		setSports.add("Basketball");
		setSports.add("Golf");
		setSports.add("Boxer");

		System.out.println("Method 1 - Iterate HashSet: ");
		demoIterateHashSet(setSports);

		System.out.println("\nMethod 2 - Iterate HashSet using java 8: ");
		demoIterateHashSetJava8(setSports);
	}

	private static void demoIterateHashSet(Set<String> setSports) {
		Iterator<String> iterator = setSports.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}

	private static void demoIterateHashSetJava8(Set<String> setSports) {
		setSports.forEach((key) -> {
			System.out.println(key);
		});
	}
}

3. Output :Iterate/loop String objects of HashSet collection (java8/example)

Method 1 - Iterate HashSet: 
null
Tennis
Cricket
Golf
Basketball
Boxer

Method 2 - Iterate HashSet using java 8: 
null
Tennis
Cricket
Golf
Basketball
Boxer
Scroll to Top