Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 range of numbers

How to generate in Java 8 range of numbers? This is practical problem, often met when writing tests. In this post we’ll cover fast implementation, comfortable, and flexible with Java 8 Streams!

Traditional for-each loop

The simplest and fastest way to get range of numbers in given range is to use simple for-each loop:

List<Integer> forLoopRange(int from, int limit) {
    List<Integer> numbers = new ArrayList<>(limit);
    for (int to = from+limit; from < to; ++from) {
    return numbers;

When we want to have a range of ints between 20 and 30 (exclusive) we can use it like that: forLoopRange(20, 10). It will produce:

[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Java 8 IntStream

Since Java 8 we can generate range of numbers using IntStream from package. It is slower, but more comfortable and speed not always is the most important factor:

List<Integer> streamRange(int from, int limit) {
    return IntStream.range(from, from+limit)

At the end we use Collectors.toList() to aggregate the numbers into a list, but equally well you could use Collectors.toSet(), because every number is different here anyway.

Let’s run it: streamRange(20, 10):

[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Note that the closing element is exclusive as usually in Java, when we operate on ranges: from – inclusive, to – exclusive.

Java 8 IntStream with closed range

In case you want to have inclusive range, IntStream has a special method for that purpose – IntStream.rangeClosed:

List<Integer> inclusiveRange(int from, int limit) {
    return IntStream.rangeClosed(from, from+limit)

Now the last number is included in range:

[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

Java 8 iterate range

A very interesting approach to generate range of numbers is IntStream.iterate(int seed, IntUnaryOperator f) method:

List<Integer> iterateStream(int from, int step, int limit) {
    return IntStream.iterate(from, i -> i+step) // next int
            .limit(limit/step) // only numbers in range

It allows to use a function that will produce the next number. In our case we want to take every step number, like here – iterateStream(20, 2, 10):

[20, 22, 24, 26, 28]

Very cool Java 8 feature! :-)


Share with the World!