This post will discuss how to initialize an array with the range 1 to n in Java.

1. Using IntStream.rangeClosed() method

In Java 8, you can use IntStream.rangeClosed(start, end) to generate a sequence of increasing values between start and end. To get a primitive integer array, you can call the toArray() method on IntStream, as shown below:

Download  Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 
To fill an existing array with ranges of numbers, you may use a lambda expression:

Download  Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2. Using IntStream.iterate() method

You can also use the IntStream.iterate() method to get a sequence in increasing order. It takes two arguments – an initial value and a function to be applied to the previous element to produce a new element. To get numbers in the range [1, n], the initial value should be 1 and the function should increase the previous value by 1. You should also restrict the number of elements in the stream to n.

Download  Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 
Java 9 introduced an overload version of the IntStream.iterate() method, which takes three arguments – an initial value, a predicate to determine when the stream must terminate, and a function to be applied to the previous element to produce a new element.

To get numbers in the range [1, n], the initial value should be 1, the predicate should limit the number of elements to n, and the function should increase the previous value by 1. Its usage is demonstrated below. Note that there is no need to call the limit() method anymore, as the stream is terminated by the predicate.

Download  Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

3. Using Arrays.setAll() method

With Java 8, you can use the Arrays.setAll() method to set the array elements with sequential integers. It takes two arguments – the array and the generator function to compute the value for each index.

Download  Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

4. Using Guava

One can also use Guava’s ContiguousSet.create() class to get a sorted set of contiguous values in the given domain within the specified range. To convert the sorted set into a primitive integer array, use Guava’s Ints.toArray() method.

Download Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

That’s all about initializing an array with the range 1 to n in Java.