Java forEach - Java 8 forEach With Examples

Java forEach method was introduced in Iterable interface in Java 8. Java 8 forEach method is another way that we can use to traverse through a collection.

Java forEach

Below code snippet shows the default implementation of java forEach method in Iterable interface. Read java 8 interface changes to learn more about default interface methods.

Java forEach method performs the given action for each element of the Iterable until all elements have been processed or exception is thrown.

Java 8 forEach List Example

Before java 8, We could iterate over a list by using for loop or iterator.

Now same thing can be performed using java forEach method as shown below.

Since Consumer is a functional interface, we can use lambda expression and write above code in one line as;

Java 8 forEach Map Example

Prior to java 8, we iterate over Map elements like below.

Since Map doesn’t extend Iterable, forEach method is added into Map interface in java 8 and below shows the default implementation.

Let’s look at a simple example how we can use java 8 forEach with Map.

Same code can be written using lambda expressions as below.

Java forEach Benefits

I don’t see too much benefit of forEach loop except when you are using it with parallel stream. A new method was added in Collection interface to get the parallel stream.

So if we have to iterate over a collection and we are not bothered about sequential iteration, then we can use parallel stream with forEach loop as shown below.

That’s all for Java forEach method. I hope you will find some use case for java 8 forEach method in parallel processing.

By admin

Leave a Reply

%d bloggers like this: