Top 10 Java Stream Recipes on Numbers

The number-stream recipes that every Java developer should know of

KRISHNA KISHORE V
6 min readJun 14, 2022

1. Use IntStream.iterate() instead of For Loops

for loops are a common way of executing the statements repeatedly. Let us say some novice programmer learning Java 8 came to you and asked about printing a range of 10 to 100 numbers. You are a hero with tons of experience in Java, laughed at this question, turned your collar up, and started writing the for loop below.

for(int i = 10; i < 100 ; i++) {
System.out.println(i);
}

As you started writing, this guy started laughing at what you are writing. You haven’t understood why the heck that guy laughing at you. You looked at his face then he also looked at his face and laughed even louder.

He controlled himself and said, dear brother, you are being too imperative. Please upgrade yourself. Then he took the pen and wrote this single line, the same but in a more declarative way. Here we go.

IntStream.iterate(10, i -> i < 100, i -> i + 1)
.forEach(System.out::println);

The argument pattern to iterate() method resembles the conventional for loop. The first argument is the seed which is the initial value, the second value is the…

--

--

KRISHNA KISHORE V

Full Stack Tech Lead | Software Consultant | Technical Content Writer