Create Array from 1 to n in Java

Introduction

In this article, we will look at How to Create an Array from 1 to n in Java. We need to Initialize Arrays in a sequence of values ranging from 1 to number N.

Knowing how we can initialize arrays in different ways will give us deeper insights into Array in Java and allow us to gain more experience with handling arrays under critical situations. Let us have a quick peek at the concept of Arrays in Java.

Array in Java

Arrays are a collection of homogenous data i.e. stores values of the same data type. In Java, we create arrays with the new keyword and allocate memory dynamically similar to the concept of Objects in Java. They can be of primitive type or an Object type.

Syntax to create Array:

int arr[] = new int[10];

Here, we create an array arr of type int and size 10.

Create Array from 1 to N in Java

Now, let us discuss in detail different ways to Create Arrays from 1 to N in Java and initialize them with a sequence of values.

Using Simple For loop in Java

When it comes to initializing arrays with a sequence of values, what better than a For loop to perform an action in a sequence.

Important points to note:

  • Use for loop and initialize each index of our array with the value: index + 1
  • This ensures that when iterating over the current index the array fills its values from 1 to a given number N.
  • Print the arrays using the Arrays.toString() method, which gives a String representation of an array object.

Let us look at the code snippet.

Output:

Using IntStream.range() method of Stream API in Java

With the advent of Java 8, the Stream API was introduced in java which brought into the picture the aspects and functionalities of Functional programming. This reduced code redundancy as well.

We will use the range() method of IntStream class that generates a sequence of increasing values between start and end of Integral values which is exclusive of the range value.

Important points to note:

  • If we want to create a stream of numbers from 1 to 10 we need to pass values into the range() method as -> range(1,11).
  • This will create a stream of integers that can be returned as an array using the toArray() method.

Note: JDK version 8 or higher must be installed to locate this approach.

Let us look at the code.

Output:

Using IntStream.rangeClosed() method of Stream API in Java

The rangeClosed() method is a variation of the range() method of the IntStream class as shown in the above example. It has similar properties to its counterpart. The only difference is that the method creates a Stream of Integers inclusive of the range value.

Hence, if we want to create a stream of numbers from 1 to 10 we need to pass values into the rangeClosed() method as -> rangeClosed(1,10).

Let us look at the code snippet for this method.

Output:

Using IntStream.iterate() method of Stream API in Java

The IntStream class provides the iterate() method with the same functionality as a for-loop. It iterates over a given value and generates a sequence of numbers in increasing order.

Important points to note:

  • If we need to generate a sequence of values we call the IntStream.iterate() method and we determine the increment value for the sequence like IntStream.iterate( 1, i -> i + 1), where 1 indicates the starting number of the sequence.
  • This ensures that the values follow a sequence. Now, to generate the number up to a certain limit we use the limit() method with the iterate() method sequence as -> limit(n), where n is the input size.
  • Next, we collect the generated sequence of integers using the toArray() method. The IntStream class by default returns an Integer []
    i.e. an Integer Wrapper class type array so there is no need to typecast the array.

Now, let us have a look at the code implementation for this approach as well.

Output:

In Java 9, the overloaded version of the iterate() method was introduced that provided an argument for the predicate to determine when the stream must terminate or to limit the sequence stream.

Features of this iterate() method in Java 9:

  • This eliminates the concern to use the limit() method as we now add the predicate to limit the number of elements to n in the stream.
  • Hence, to use this iterate() method with the limiting functionality we define it like this: iterate( 1, i  -> i <= n, i -> i+1), where 1 indicates the starting number of the sequence.

Let us have a quick look at this code snippet as well.

Output:

Using the Stream class of Stream API in Java

We can also use the Stream class as an alternative to the above-discussed ways with the IntStream class. We can use the iterate() method of the Stream class in the same way we use the IntStream.iterate() method.

Important points to note:

  • We will use an array of Integer Wrapper class type then use the limit() method to terminate the stream and collect the stream into an array using the toArray() method.
  • The toArray() method of the Stream class returns an Object[] i.e. Object class type array by default. Hence, It becomes necessary to typecast this Object[] into an Integer[] type.
  • We typecast the generated stream to Integer[] type using the toArray() method like this: toArray(Integer[]::new) . This converts the returned array to an Integer array.

Let us look at the code implementation below.

Output:

Using Arrays.setAll() method in Java

In Java 8, the setAll() method was introduced in the Arrays class. It is a very useful method to set the array elements with sequential integers or a fixed value through the entire length of the array.

Important points to note:

  • It accepts two arguments – the array and the predicate that computes the value for each index and returns nothing as it is a setter method.
  • Using the setAll() method, we can set the array with a fixed value as well. Here we write a predicate that generates a sequence of integers and call the method as setAll(arr, i -> i+1), where arr is the array to fill.

Let us look at the code implementation for this approach.

Output:

Using Eclipse Collections Framework in Java

The Eclipse Collections Framework is a powerful framework that provides its own Collection framework in Java. It provides powerful and reusable Java components, dependencies and API’s that we can embed into our applications and programs.

Here, we can use the Interval class of org.eclipse.collections.impl library by importing its dependency into our Java application. For ease, we will use the JAR file component of the Eclipse Collections Impl package.

To setup the JAR file component for this package we follow these steps:

  1. Download the Eclipse Collection Main Library JAR and the Eclipse Collections API JAR component.
  2. Download only the JAR component from the above two links, as we need both jars to import two components into our Java application(Version might vary according to the latest updates).
  3. Go to your IDE (Eclipse EE/IntelliJ) then right-click on the package name and go to -> Configure Build Path.
  4. Go to libraries -> Click on Classpath -> Add External JAR’s.
  5. Select both the Eclipse Collection Main Library and API JAR file – eclipse collections-11.1.0 and eclipse-collections-api-11.1.0, then click Apply and close. 

The JAR will then be added to your Java Application after this we can just import the required classes from this package. Now, let us look into the implementation.

We need to basically import two classes :

  1. LazyIterable class from Eclipse Collections API JAR. Package specification – import org.eclipse.collections.api.LazyIterable 
  2. Interval class from Eclipse Collections Main Library. Package specification – import org.eclipse.collections.impl.list.Interval;

Important Points for implementation:

  • We will use the oneTo() method of the Interval class to generate a sequence of increasing numbers. It accepts only one argument – the limiting end of the sequence.
  • We will provide N, the array size as an input to this method.
  • The method returns a collection of type Interval which we can convert to an array using the toArray() method but we need to use Integer Wrapper class type array i.e. Integer[].

Let us look at the implementation in the code.

Output:

Using Google Guava Library in Java

The Google Guava API Library is an open-source set of common core Java libraries, mainly developed by Google engineers that provide powerful and reusable Java components and dependencies that we can embed into our Java applications.

You can use the Google Guava Library on any maven project as below.
Here is the dependency which you need to add for guava in pom.xml.

Here, we will use the combination of Range, DiscreteDomain, ContiguousSet, and Ints from Guava or from the Google Common package to create a sequence of integers and initialize our array with it up to a given value N.

We can import the dependency as well but here we will use the JAR component for clarity.

Once we have added the dependency, we can import the required classes from this package. We basically need to import four classes from this package.

  1. ContiguousSet class
  2. DiscreteDomain class
  3. Range class
  4. Ints class.

Important points for implementation:

  • Create a Contiguous Set or a sequence of integers using the ContiguousSet.create() method wherein we can specify the range with a start and end value using the Range.closed() method.
  • Pass the start and end value to the closed() method which is exclusive of the end value like this: Range.closed(1, n), where 1 is the start of the sequence and n is the end.
  • Specify type of value or the Domain using the DiscreteDomain.integers() method in ContiguousSet.create()method
  • Get our Contiguous Set and then convert it into an array using the Ints.toArray() method by passing the set as an argument.

Now let us look at the implementation of this approach.

Output:

That’s all for the article we had a look over 8 ways to Create an Array from 1 to N in Java with working examples from basic to advanced levels. You can try out these examples in your local IDE and follow the explanations in detail.

Feel free to reach out to us for any suggestions/doubts.

 

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *