forEach method in Java 8

/, Java 8/forEach method in Java 8

forEach method :

Java 8 introduced a new method forEach() to process each element of Collection or Stream forEach() method present in two interfaces one is Iterable and other is Stream.

Method Signature:

Collection classes which extends Iterable interface can use forEach method to iterate elements. This method takes a single parameter which is Consumer functional interface. As this is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

Simple example using lambda:

Simple example using method reference:

Simple example using Stream :

Simple example using Consumer :

Enhanced for-each loop vs forEach method :

Enhanced for-each loop and forEach method both provide same functionality, iterate through elements in a collection. But the major difference is forEach method provide declarative mechanism, means for enhanced for-each loop developer has to write iteration process externally but forEach method API do the iteration process internally.

Simple example using enhanced for-each loop :

Leave a Reply