AlikElzin-kilaka AlikElzin-kilaka - 25 days ago 7
Java Question

How to iterate x times using Java 8 stream?

I have an old style

for
loop to do some load tests:

For (int i = 0 ; i < 1000 ; ++i) {
if (i+1 % 100 == 0) {
System.out.println("Test number "+i+" started.");
}
// The test itself...
}


How can I use new Java 8 stream API to be able to do this without the
for
?


Also, the use of the stream would make it easy to switch to parallel stream. How to switch to parallel stream?

* I'd like to keep the reference to
i
.

Answer
IntStream.range(0, 1000)
         /* .parallel() */
         .filter(i -> i+1 % 100 == 0)
         .peek(i -> System.out.println("Test number " + i + " started."))
         /* other operations on the stream including a terminal one */;

If the test is running on each iteration regardless of the condition (take the filter out):

IntStream.range(0, 1000)
         .peek(i -> {
             if (i + 1 % 100 == 0) {
                 System.out.println("Test number " + i + " started.");
             }
         }).forEach(i -> {/* the test */});

Another approach (if you want to iterate over an index with a predefined step, as @Tunaki mentioned) is:

IntStream.iterate(0, i -> i + 100)
         .limit(1000 / 100)
         .forEach(i -> { /* the test */ });

There is the awesome overloaded Stream.iterate(seed, condition, unaryOperator) in JDK 9 which perfectly fits your situation and is designed to make a stream finite and replace old-fashioned fors:

Stream<Integer> stream = Stream.iterate(0, i -> i < 1000, i -> i + 100);