Introduced in Java 8, the forEach loop provides programmers a new concise and interesting way for iterating over a list of elements. We will see how to use forEach with collections, what kind of argument it takes and how this loop differs from the enhanced for-loop. In java 8 with forEach, we can iterate over a collection and perform a given action on each element – by just passing a class that implements the Consumer interface

Consumer Interface

Consumer interface is a functional interface (an interface with a single abstract method). It accepts an input and returns no result

Both forEach and For Loop provide the same functionality. Looping through elements in a collection and only the main difference between the two of them is that they are different iterators – the enhanced for-loop is an external iterator whereas the new forEach method is an internal one.

Internal Iterator - iterator manage the iteration in the background and leaves the programmer to just code what is meant to be done with the elements of the collection, rather than managing the iteration and making sure that all the elements are processed one-by-one.

External Iterator - If need more control on the iterator and need to preform some checks and operation on each element then External Iterator can be used.

Lambda Expression - lambda expression is an anonymous representation of a function descriptor of a functional interface.

Method Reference - where a method already exists to perform an operation on the class, this syntax can be used instead of the normal lambda expression

All these types are listed in the below sample program and we can get to know about each of these implementation in Java 8