Java 8 forEach() method is used to iterate over elements of a collection using functional programming concepts. In this chapter, you will learn about the forEach() method, its signature and usages along with examples.
The forEach() method is introduced in Java 8 and it is used to iterate over elements of a collection in a simple way. It is defined in the Iterable interface that means all collection classes (like List, Set, etc.) can use this method.
Instead of writing long loops, we can use forEach() along with a lambda expression to perform operations on each element.
The syntax to use forEach() method is as follows:
A key advantage of forEach() over traditional loops is its compactness and readability, as it uses lambda expressions to handle iteration logic that reduces the mental effort required to understand the code and makes the code easier to maintain.
Additionally, forEach() promotes a more functional programming style by encouraging separation of concerns and minimizing direct mutation.
The following examples demonstrate how the forEach() method is used to iterate over elements in different ways.
In this example, the forEach() method is used with a lambda expression to print each element of the collection.
Output:
------------Iterating by passing lambda expression-------------- Football Cricket Chess Hocky
In this example, the forEach() method is used with a method reference instead of a lambda expression.
Output:
------------Iterating by passing method reference--------------- Football Cricket Chess Hocky
In this approach, the forEach() method uses a lambda expression to define the operation that should be performed on each element.
In this example, each element of the list is printed using a lambda expression.
Output:
Football Cricket Chess Hockey
In this approach, the forEach() method uses a method reference instead of a lambda expression.
In this example, each element of the list is printed using a method reference.
Output:
Football Cricket Chess Hockey
We request you to subscribe our newsletter for upcoming updates.