Java 8

Java 8 forEach with index Example

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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Python

How to access for loop index in Python

The built-in Python enumerate function is a better way to access the for loop index. How to access for loop index in Python: The builtin enumerate function available…

Ask a question or leave a comment