In older versions of java like before java 8, we usually iterate for loop using indexes, for example, if we want to print numbers from 0 to 10 we would generally write code like below.

for (int i = 0; i <10 ; i++) {
    System.out.print(i);
}

This example helps you to simulate the same thing using Java 8 forEach method.

Java 8 forEach with index Example:

Java 8 provides IntStream/DoubleStream interfaces to deal with indexes. The same above example can write using Java 8 or above like below.

ForEach.java
IntStream.range(0,10)
                .forEach(System.out::print);

A simple use case:

Adding all even numbers from 0 to 10.

ForEach.java
int sum = IntStream.range(0,10)
                .filter(ele->ele%2==0)
                .sum();
System.out.println(sum);//20

References:

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment