Java 8 forEach with index Example

By | 2019-04-02T03:15:33+05:30 April 2nd, 2019|java8|

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:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment