How to use IntStream range in Java

Very often, I encounter a situation in which I need to loop through a collection in Java. While looping through it sequentially, I usually want to use a temporal loop count variable as a variable with which I will be working inside the loop.

Java 8 come with beautiful solution on this pattern. It is called IntStream.

Example of IntStream range() method

Static method range(startInclusive, endExclusive) of IntStream class returns a sequential ordered of integer numbers from range of startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1. Therefore startInclusive is inclusive initial value and endInclusive is exclusive upper bound.

All this is equivalent of sequence increasing values sequentially using a for loop as follows:
for (int i = startInclusive; i < endInclusive ; i++) { ... }

Example code:

IntStream intStream = IntStream.range(1, 5);
intStream.forEach(i -> {
System.out.print(i + " ");
});

Example output:
1 2 3 4

Example of IntStream rangeClosed() method

Static method rangeClosed(startInclusive, endInclusive) of IntStream class returns a sequential ordered of integer numbers from range of startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1. Therefore startInclusive is inclusive initial value and endInclusive is inclusive upper bound.

All this is equivalent of sequence increasing values sequentially using a for loop as follows:
for (int i = startInclusive; i <= endInclusive ; i++) { ... }

Example code:

IntStream intStream = IntStream.rangeClosed(1, 5);
intStream.forEach(i -> {
System.out.print(i + ", ");
});

Example output:
1 2 3 4 5

This entry was posted in Language basics and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.