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 Share on X

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..!!! Share on X

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

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak