This post will discuss how to generate a list of sequential integers in Java. The solution should create a list with ranges of numbers between 1 and n.

1. Using IntStream.range() method

In Java 8 or later, this can be easily done using Streams without looping or using third-party libraries. The idea is to use the IntStream.range(…) method to generate a stream of increasing integers between the specified indices. To get a list of integers, you can box the primitive int stream and collect the stream elements into a list.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

2. Using IntStream.iterate() method

Another alternative is to use the IntStream.iterate(…) method to get an infinite sequential ordered IntStream. It is produced by applying a function f to an initial element x, thereby producing a Stream consisting of x, f(x), f(f(x)), etc.

Here’s complete usage of this method:

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
The above solution restricts the number of elements in the infinite stream to n using the limit() method. A better way to do it in Java 9 and above is with the overloaded 3-arg IntStream.iterate(…) method, which returns a finite sequential ordered IntStream, terminating on satisfying the specified predicate.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

3. Using Guava Ranges

Another plausible solution is to use Guava Ranges to create a sorted set of contiguous values (ContiguousSet) with the elements of a range of a discrete domain. To get a list, call the asList() method on the sorted set.

Its usage is demonstrated below.

Download Code

Output:

[1, 2, 3, 4, 5]

That’s all about generating a list of sequential integers in Java.