Iterating Set using forEach() in Java 8

In one of the previous article, we have discussed various ways to iterate through Set

Various ways to iterate through Set

  1. Enhanced for-loop (introduced in Java 1.5 version)
  2. Iterating using Iterator of Collection interface
  3. Read different ways to iterate Set

 

Example 1: Iterating Set using enhanced for-loop introduced in Java 1.5 version

  • With enhanced for-loop we can iterate through Set as demonstrated below,

IteratingSetUsingEnhancedForLoop.java

package in.bench.resources.java.collection.list;

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

public class IteratingSetUsingEnhancedForLoop {

	public static void main(String[] args) {

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

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

		// Iterating Set using enhanced for-loop
		System.out.println("Iterating Set using enhanced for-loop\n");
		for(String founder : founders) {
			System.out.println(founder);
		}
	}
}

Output:

Iterating Set using enhanced for-loop

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

 

Example 2: Iterating HashSet using enhanced for-each loop introduced in Java 1.8 version

  • In Java 8, we can iterate Set using Iterable.forEach() loop

IteratingSetUsingForEachLoopInJava8.java

package in.bench.resources.java.collection.list;

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

public class IteratingSetUsingForEachLoopInJava8 {

	public static void main(String[] args) {

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

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

		// Iterating Set using forEach() in Java 8
		System.out.println("Iterating Set using forEach() in Java 8\n");
		founders.forEach(founder -> System.out.println(founder)); 
	}
}

Output:

Iterating Set using forEach() in Java 8

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

Note: line no. 25 for much improved forEach loop in Java 8

 

From above example, HashSet

  • allows only unique elements
  • null object is allowed; but maximum of one
  • while iterating, elements retrieved in random-order

To conclude, now there are 3 ways to iterate Set

 

References:

 

Happy Coding !!
Happy Learning !!

How to reverse LinkedHashSet contents
Various ways to iterate through HashSet - 3 ways