Convert Object array to Integer array in Java

In this post, we will see how to convert Object array to Integer array in Java.


 

1. Naive

Simple approach is to use 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. System.arraycopy()

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. Arrays.copyOf()

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

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

4. List.toArray()

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

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

5. Java 8

Java 8 provides another simple approach to convert object array to integer array. Below 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 toArray() method to accumulate elements of the stream into a new integer array.
     

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz