Close

Java 8 Streams - IntStream.range Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.IntStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.IntStreamIntStreamLogicBig

Method:

static IntStream range(int startInclusive,
                       int endExclusive)

This method returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.


Examples


package com.logicbig.example.intstream;

import java.util.stream.IntStream;

public class RangeExample {

public static void main(String... args) {
System.out.println("-- range --");
IntStream intStream = IntStream.range(4, 7);
intStream.forEach(System.out::println);
}
}

Output

-- range --
4
5
6




This example shows how Java 8 streams are lazy.

package com.logicbig.example;

import java.util.stream.IntStream;

import static com.logicbig.example.LogUtil.log;

public class LazyExample {

public static void main (String[] args) {
IntStream stream = IntStream.range(1, 5);
stream = stream.peek(i -> log("starting", i))
.filter(i -> {
log("filtering", i);
return i % 2 == 0;
})
.peek(i -> log("post filtering", i));
log("Invoking terminal method count.");
log("The count is", stream.count());
}
}

Output

15:40:47.815 - Invoking terminal method count.
15:40:47.825 - starting - 1
15:40:47.827 - filtering - 1
15:40:47.828 - starting - 2
15:40:47.830 - filtering - 2
15:40:47.831 - post filtering - 2
15:40:47.833 - starting - 3
15:40:47.834 - filtering - 3
15:40:47.836 - starting - 4
15:40:47.837 - filtering - 4
15:40:47.839 - post filtering - 4
15:40:47.840 - The count is - 2
Original Post




See Also