Java 8 – Stream forEach method with examples

In this article, we will discuss forEach() method which is used to iterate through Collection, Map and Stream in detail with examples

forEach() method is introduced in Collection and Map in addition to Stream, so we can iterate through elements of Collection, Map or Stream. We will see through below items along with examples,

  1. Iterating through Stream using forEach() method
  2. Iterating through Collection classes List, Set and Queue using forEach() method
  3. Iterating through Map using forEach() method

1. Stream forEach method :

  • This Stream method is a terminal operation which is used to iterate through all elements present in the Stream
  • Performs an action for each element of this stream
  • Input to the forEach() method is Consumer which is Functional Interface
  • For Sequential stream pipeline, this method follows original order of the source
  • But for Parallel stream pipeline, this method doesn’t guarantee original order of the source
  • To bring uniformity between original source and parallel stream order we can use forEachOrdered() method which we will see in next article
  • forEach() method is non-interfering with other elements in the Stream
  • Method signature :- void forEach(Consumer action)

1.1 Stream forEach method examples :

  • Here, we will go through few examples for forEach() method of Stream API
  • Using forEach() method, we will iterate through all elements and print to console using lambda expression as well as method reference

1.1.1 To filter even numbers and print to console using lambda expression

  • A list contains first 10 natural numbers
  • We are applying condition to filter out only EVEN numbers using filter() method
  • Finally, printing to console using Stream’s forEach() method using Lambda expression
package net.bench.resources.stream.foreach.example;

import java.util.Arrays;
import java.util.List;

public class StreamForEachLambdaExpression {

	public static void main(String[] args) {

		// create List of first 10 natural numbers
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		System.out.println("1. Natual numbers in the original List :- \n\n" + numbers);


		// filter only EVEN numbers and print to console

		System.out.println("\n\n2. Only EVEN numbers :- \n");

		numbers // original source
		.stream() // 1. get stream from source
		.filter(i -> i%2 == 0) // 2. filter intermediate operation
		.forEach(num -> System.out.println(num)); // 3. forEach terminal operation
	}
}

Output:

1. Natual numbers in the original List :- 

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


2. Only EVEN numbers :- 

2
4
6
8
10

1.1.2 Map all String elements to Upper Case and print to console using Method Reference

  • A list contains String elements
  • We are applying map function to convert to upper case using map() method
  • Finally, printing to console using Stream’s forEach() method using Method Reference
package net.bench.resources.stream.foreach.example;

import java.util.Arrays;
import java.util.List;

public class StreamForEachMethodReference {

	public static void main(String[] args) {

		// create List of String elements
		List<String> names = Arrays.asList(
				"Vijay",
				"Ajith",
				"Kamal",
				"Rajini",
				"Dhanush",
				"Simbhu",
				"Surya",
				"Vikram",
				"Arya",
				"Vishal"
				);

		System.out.println("1. Names in the original List :- \n\n" + names);


		// convert names to Upper case and print to console

		System.out.println("\n\n2. Names after upper case :- \n");

		names // original source
		.stream() // 1. get stream from source
		.map(name -> name.toUpperCase()) // 2. map intermediate operation
		.forEach(System.out::println); // 3. forEach terminal operation
	}
}

Output:

1. Names in the original List :- 

[Vijay, Ajith, Kamal, Rajini, Dhanush, Simbhu, Surya, Vikram, Arya, Vishal]


2. Names after upper case :- 

VIJAY
AJITH
KAMAL
RAJINI
DHANUSH
SIMBHU
SURYA
VIKRAM
ARYA
VISHAL

1.1.3 To sort Students based on ranks and print to console

  • Few Student information stored in the List with attributes like name, marks, rank
  • We are going to sort Student information based on rank they obtained using sorted() method
  • Finally, printing to console using Stream’s forEach() method using Lambda expression
package net.bench.resources.stream.foreach.example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Student {

	// member variables

	String name;
	int marks;
	int rank;

	// public constructor

	public Student(String name, int marks, int rank) {
		super();
		this.name = name;
		this.marks = marks;
		this.rank = rank;
	}

	// override toString() method

	@Override
	public String toString() {
		return "Student [name=" + name + ", marks=" + marks + ", rank=" + rank + "]";
	}
}


public class StreamForEachSortStudentInfo {

	public static void main(String[] args) {

		// List of Students
		List<Student> studentList = Arrays.asList(
				new Student("Vijay", 97, 1),
				new Student("Ajith", 71, 3),
				new Student("Surya", 64, 4),
				new Student("Arya", 83, 2),
				new Student("Siva", 55, 5)
				);

		System.out.println("1. Student list without sorting :- \n");

		// print to console using Java 8 forEach
		studentList.forEach(System.out::println);



		// sorting Student List based on ranks
		List<Student> rankList = studentList
				.stream() // 1. get stream
				.sorted((s1, s2) -> Integer.valueOf(s1.rank)
						.compareTo(Integer.valueOf(s2.rank))) // 2. sort intermediate operation
				.collect(Collectors.toList()); // 3. collect terminal operation

		System.out.println("\n\n2. Student information in ascendng order of ranks :- \n");

		// print to console using Java 8 forEach
		rankList.forEach(rank -> System.out.println(rank));
	}
}

Output:

1. Student list without sorting :- 

Student [name=Vijay, marks=97, rank=1]
Student [name=Ajith, marks=71, rank=3]
Student [name=Surya, marks=64, rank=4]
Student [name=Arya, marks=83, rank=2]
Student [name=Siva, marks=55, rank=5]


2. Student information in ascendng order of ranks :- 

Student [name=Vijay, marks=97, rank=1]
Student [name=Arya, marks=83, rank=2]
Student [name=Ajith, marks=71, rank=3]
Student [name=Surya, marks=64, rank=4]
Student [name=Siva, marks=55, rank=5]

2. Iterable forEach method :

  • This is newly introduced method in Iterable interface in Java 1.8 version and Collection interface extends Iterable interface
  • So, all implementing classes of List, Set and Queue can use forEach() method to iterate through all elements
  • Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception
  • Exceptions thrown by the action are relayed to the caller
  • Input to the forEach() method is Consumer which is Functional Interface
  • Method signature :- default void forEach(Consumer<? super T> action)

2.1 Iterable forEach method examples :

  • Here, we will go through examples for forEach() method for each of the implementing classes of List, Set and Queue
  • In the below example, using forEach() method we will iterate through all elements present inside implementing classes of List, Set and Queue like ArrayList, HashSet and PriorityQueue respectively and print to console

2.1.1 Iterate through List and print to console

  • Below examples contains 2 lists where 1st list contains String elements and 2nd list contains Integer elements
  • We will iterate through all these elements using Iterable’s forEach() method and print to console
  • Note:- we will print to console using both lambda expression as well as method reference
package net.bench.resources.stream.foreach.example;

import java.util.Arrays;
import java.util.List;

public class CollectionForEachList {

	public static void main(String[] args) {

		// create List of String elements
		List<String> fruitList = Arrays.asList(
				"Apple",
				"Banana",
				"Grapes",
				"WaterMelon",
				"MuskMelon"
				);

		// print to console using Collection forEach method

		System.out.println("1. Iterable forEach method using lambda expression : \n");

		fruitList.forEach(fruit -> System.out.println(fruit));



		// create List of Integers
		List<Integer> primeNumbers = Arrays.asList(19, 23, 41, 59, 97);

		// print to console using Collection forEach method

		System.out.println("\n\n2. Iterable forEach method using method reference : \n");

		primeNumbers.forEach(System.out::println);
	}
}

Output:

1. Iterable forEach method using lambda expression : 

Apple
Banana
Grapes
WaterMelon
MuskMelon


2. Iterable forEach method using method reference : 

19
23
41
59
97

2.1.2 Iterate through Set and print to console

  • Below examples contains 2 set where 1st set contains String elements and 2nd set contains Integer elements
  • We will iterate through all these elements using Iterable’s forEach() method and print to console
  • Note:- we will print to console using both lambda expression as well as method reference
package net.bench.resources.stream.foreach.example;

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

public class CollectionForEachSet {

	public static void main(String[] args) {

		// create Set of String elements
		Set<String> uniqueDepartments = new HashSet<>(Arrays.asList(
				"Computer",
				"Manufacturing",
				"Admin",
				"Electronics",
				"Telecommunication"
				));

		// print to console using Collection forEach method

		System.out.println("1. Iterable forEach method using lambda expression : \n");

		uniqueDepartments.forEach(dept -> System.out.println(dept));



		// create Set of Integers
		Set<Integer> primeNumbers = new HashSet<>(Arrays.asList(19, 23, 41, 59, 97));

		// print to console using Collection forEach method

		System.out.println("\n\n2. Iterable forEach method using method reference : \n");

		primeNumbers.forEach(System.out::println);
	}
}

Output:

1. Iterable forEach method using lambda expression : 

Computer
Electronics
Telecommunication
Manufacturing
Admin


2. Iterable forEach method using method reference : 

97
19
23
41
59

2.1.3 Iterate through Queue and print to console

  • Below examples contains 2 Queues where 1st Queue contains String elements and 2nd Queue contains Integer elements
  • We will iterate through all these elements using Iterable’s forEach() method and print to console
  • Note:- we will print to console using both lambda expression as well as method reference
package net.bench.resources.stream.foreach.example;

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

public class CollectionForEachQueue {

	public static void main(String[] args) {

		// create Set of String elements
		Queue<String> partsOfComputer = new PriorityQueue<>(Arrays.asList(
				"CPU",
				"Monitor",
				"Keyboard",
				"Mouse",
				"Motherboard"
				));

		// print to console using Collection forEach method

		System.out.println("1. Iterable forEach method using lambda expression : \n");

		partsOfComputer.forEach(dept -> System.out.println(dept));



		// create Set of Integers
		Queue<Integer> primeNumbers = new PriorityQueue<>(Arrays.asList(19, 23, 41, 59, 97));

		// print to console using Collection forEach method

		System.out.println("\n\n2. Iterable forEach method using method reference : \n");

		primeNumbers.forEach(System.out::println);
	}
}

Output:

1. Iterable forEach method using lambda expression : 

CPU
Monitor
Keyboard
Mouse
Motherboard


2. Iterable forEach method using method reference : 

19
23
41
59
97

3. Map forEach method :

  • This is newly introduced method in Map interface in Java 1.8 version
  • So, all implementing classes of Map like HashMap, LinkedHashMap and TreeMap can use forEach() method to iterate through all Key-Value pairs or entries
  • Performs the given action for each entry in this map until all entries have been processed or the action throws an exception
  • Exceptions thrown by the action are relayed to the caller
  • Input to the forEach() method is BiConsumer which is Functional Interface
  • Method signature :- default void forEach(BiConsumer<? super K, ? super V> action)

3.1 Map forEach method examples :

3.1.1 Iterate through Map and print to console

  • HashMap contains 5 Key-Value pairs
  • We will iterate through all these Key-Value pairs using Map’s forEach() method and print to console
  • Note:- we will print to console using both lambda expression only
package net.bench.resources.stream.foreach.example;

import java.util.HashMap;
import java.util.Map;

public class MapForEachIteratingExample {

	public static void main(String[] args) {

		// create Map
		Map<Integer, String> rankCompany = new HashMap<>();

		// add few entries in HashMap

		rankCompany.put(1, "Google");
		rankCompany.put(2, "Microsoft");
		rankCompany.put(3, "Yahoo");
		rankCompany.put(4, "Oracle");
		rankCompany.put(5, "Facebook");


		// iterate and print to console - lambda expression

		System.out.println("1. Iterating using Map's forEach method - Lambda Expression :- \n");

		rankCompany.forEach(
				(key, value) -> System.out.println("Rank : " + key + "\tCompany : " + value)
				);
	}
}

Output:

1. Iterating using Map's forEach method - Lambda Expression :- 

Rank : 1	Company : Google
Rank : 2	Company : Microsoft
Rank : 3	Company : Yahoo
Rank : 4	Company : Oracle
Rank : 5	Company : Facebook

3.1.2 Iterate through Map using EntrySet and print to console

  • Example 1 :- HashMap contains 5 entries
  • We will iterate through Map’s EntrySet using forEach() method and print to console using lambda expression
  • Example 2 :- TreeMap contains 5 entries which keeps Map naturally sorted based on keys
  • We will iterate through Map’s EntrySet using forEach() method and print to console using method reference
  • Note:- below examples prints Map’s EntrySet to console using lambda expression as well as method reference
package net.bench.resources.stream.foreach.example;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class MapEntrySetIteratingUsingForEach {

	public static void main(String[] args) {

		// create Map
		Map<Integer, String> rankCompany = new HashMap<>();

		// add few entries in HashMap

		rankCompany.put(1, "Google");
		rankCompany.put(2, "Microsoft");
		rankCompany.put(3, "Yahoo");
		rankCompany.put(4, "Oracle");
		rankCompany.put(5, "Facebook");


		// iterate and print to console - lambda expression

		System.out.println("1. Iterating Map.EntrySet using forEach method"
				+ " - Lambda Expression :- \n");

		rankCompany
		.entrySet()
		.forEach(
				entry -> System.out.println("Rank : " + entry.getKey() 
				+ "\tCompany : " + entry.getValue())
				);



		// create another Map
		Map<String, String> ceoCompany = new TreeMap<>();

		// add few entries in TreeMap

		ceoCompany.put("Sundar Pichai", "Google");
		ceoCompany.put("Satya Nadella", "Microsoft");
		ceoCompany.put("Marissa Mayer", "Yahoo");
		ceoCompany.put("Jeff Bezos", "Amazon");
		ceoCompany.put("Mark Zuckerberg", "Facebook");


		// iterate and print to console - Method Reference

		System.out.println("\n\n2. Iterating Map.EntrySet using forEach method"
				+ " - Method Reference :- \n");

		ceoCompany.entrySet().forEach(System.out::println);
	}
}

Output:

1. Iterating Map.EntrySet using forEach method - Lambda Expression :- 

Rank : 1	Company : Google
Rank : 2	Company : Microsoft
Rank : 3	Company : Yahoo
Rank : 4	Company : Oracle
Rank : 5	Company : Facebook


2. Iterating Map.EntrySet using forEach method - Method Reference :- 

Jeff Bezos=Amazon
Marissa Mayer=Yahoo
Mark Zuckerberg=Facebook
Satya Nadella=Microsoft
Sundar Pichai=Google

References:

Happy Coding !!
Happy Learning !!

Java 8 - Difference between map() and flatMap() in Stream API