This post will discuss how to convert the object array to an Integer array in Java.

1. Naive solution

A simple approach is to use a regular for-loop to iterate over the object array, and for every object, we cast it to Integer and assign it to the Integer array.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

2. Using System.arraycopy() method

We can use System.arraycopy() that copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

3. Using Arrays.copyOf() method

We can also use Arrays.copyOf() to copy the specified array to an array of the specified type.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

4. Using List.toArray() method

Here we first convert the object array to a list of objects and then use the toArray(T[]) method to dump the list into a newly allocated Integer array.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

5. Using Java 8

Java 8 provides another simple approach to convert object array to integer array. Following are the steps:

  1. Convert the specified object array to a sequential Stream.
  2. Use Stream.map() to convert every object in the stream to their integer representation.
  3. Use the toArray() method to accumulate the stream elements into a new integer array.

The following program demonstrates it:

Download  Run Code

Output:

[1, 2, 3, 4, 5]

That’s all about converting an Object array to an Integer array in Java.