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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /** * Using Java, Square of Numbers using Tradional For Loop * @author Deepak Verma * */ public class Square_of_Numbers_using_For_Loop_Java { public static void main(String[] args) { // Traditional For loop for (int i = 1; i <= 10; i++) { int square = i * i; System.out.println(square); } } } |
Now, let’s rewrite it using Java 8 Stream API and lambda expression:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.stream.IntStream; /** * Using Java 8, Square of Numbers using Stream and Lambda Expression * @author Deepak Verma * */ public class Square_of_Numbers_using_Lambda_and_Stream_Java8 { public static void main(String[] args) { // Using lambda expression and Stream IntStream.rangeClosed(1, 10) .map(i -> i * i) .forEach(System.out::println); } } |
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:
1 2 3 4 5 6 7 8 9 10 | 1 4 9 16 25 36 49 64 81 100 |
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:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: