Skip to main content

Java 8 - Streams - Replace Traditional for Loops

Greetings!

It is very common to have numeric iterations like below;


for (int i = 1; i <= 100; i++) {
    // do something
}


Java 8 has static methods for this common task in IntStream and LongStream.

IntStream intStream = IntStream.rangeClosed(1, 100);

// Inclusive. Up to 100: 1, 2, ..., 99, 100
IntStream.rangeClosed(1, 100).forEach(System.out::println);

// Exclusive. Up to 99: 1, 2, ..., 98, 99
IntStream.range(1, 100).forEach(System.out::println);

// With Steps: 1, 2, ..., 98, 100
IntStream.iterate(0, i -> i + 2).limit(50).forEach(System.out::println);

Note that iterate produces an infinite stream.

Comments