Top 10 Java Stream Recipes on Numbers

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



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++) {

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)

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 predicate upon the failure of which the iterate() method comes out, and the third argument is the update operation that occurs for each iteration.

2. Use IntStream.range() instead of IntStream.iterate()

The same problem mentioned above can be dealt with in a more simple and elegant way using IntStream.range() as below.

IntStream.range(10, 100).forEach(System.out::println);

This prints only 10 to 99. Because the start value 10 is inclusive and the end value 100 is exclusive. If we want both to be inclusive just use IntStream.rangeClosed() as below.

IntStream.rangeClosed(10, 100).forEach(System.out::println);

3. Generating Random Numbers

At times, we need to unit test a number-based algorithm or a number-based compute-intensive task. Generating random numbers is…




Full Stack Tech Lead | Software Consultant | Technical Content Writer