Difference between Collection.stream().forEach() and Collection.forEach() in Java


Collection.stream().forEach() and Collection.forEach() both are used to iterate over collection. 

Collection.forEach()  uses the collection’s iterator. Most of the collections doesn’t allow the structurally modification while iterating over them. If any element add or remove while iteration they will immediately throw concurrent modification exception. If Collection.forEach() is iterating over the synchronized collection then they will lock the segment of the collection and hold it across all the calls. 

Collection.stream().forEach() is also used for iterating the collection but it first convert the collection to the stream and then iterate over the stream of the collection therefore the processing order is undefined. It also throws the concurrent modification exception, if any structural changes happened while iterating over them it will throw an exception immediately.

Sr. No.
Key
Collection.forEach()
Collection.stream().forEach()

1

Basic 

Collection.forEach() uses the collection’s iterator

Collection.stream().forEach() is also used for iterating the collection but it first convert the collection to the stream and then iterate over the stream of the collection

2

Order 

It always executed in the iteration order of the Iterable, if one is specified.

Order is not defined 

3

Lock 

If iteration is happening over the synchronized collection then It lock the collection and hold it across all the calls 

It does not lock the collection 

4. 

Exception 

It will immediately throw an exception in the case of any structural modification happened  in the collection 

 Exception will be thrown later

Example Collection.stream().forEach

import java.util.ArrayList;
import java.util.List;
public class Main {
   public static void main(String[] args) {
      List list= new ArrayList();
      list.add("Ram");
      list.add("TutorialPoints");
      list.stream().forEach(System.out::print);
   }
}

Example Collection.forEach

import java.util.ArrayList;
import java.util.List;
public class Main {
   public static void main(String[] args) {
      List list= new ArrayList();
      list.add("Ram");
      list.add("TutorialPoints");
      list.forEach(System.out::print);
   }
}

Updated on: 21-Jan-2020

632 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements