Java 8 gave us the opportunity to get over the traditional structure of ‘FOR’ loops and make it more effective and concise using Stream and Lambda expression.  Rewrite Traditional For Loops with Stream and Lambda expression in Java

Get over Traditional FOR Loop and rewrite using Lambda and Stream in Java 8 Click To Tweet

Let’s consider a simple example where we have a traditional loop that prints the squares of numbers from 1 to 10:

 

 

Now, let’s rewrite it using Java 8 Stream API and lambda expression:

 

 

In this example:

  • IntStream.rangeClosed(1, 10) creates a stream of integers from 1 to 10.
  • .map(i -> i * i) applies a lambda expression to square each element in the stream.
  • .forEach(System.out::println) prints each squared value to the console.

 

Output:

find first non repeated character in a string using Java 8

It demonstrates how we can use the Stream API and lambda expressions to achieve the same result as a traditional loop, often in a more concise and expressive manner.

 

No more Traditional FOR Loops, Replace them with Stream and Lambda in Java 8..!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: