I often encounter a situation where I need to loop through a collection in Java. While looping through the collection 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