How to convert Integer[] to int[] array in Java?

36,656

Solution 1

You can use Stream APIs of Java 8

int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();

Solution 2

If you can consider using Apache commons ArrayUtils then there is a simple toPrimitive API:

public static double[] toPrimitive(Double[] array, double valueForNull)

Converts an array of object Doubles to primitives handling null.

This method returns null for a null input array.

Solution 3

Using Guava, you can do the following:

int[] intArray = Ints.toArray(intList);

If you're using Maven, add this dependency:

<dependency>
   <groudId>com.google.guava</groupId>
   <artifactId>guava</artifactId>
   <version>18.0</version>
</dependency>

Solution 4

If you have access to the Apache lang library, then you can use the ArrayUtils.toPrimitive(Integer[]) method like this:

int[] primitiveArray = ArrayUtils.toPrimitive(objectArray);

Solution 5

You can download the org.apache.commons.lang3 jar file which provides ArrayUtils class.
Using the below line of code will solve the problem:

ArrayUtils.toPrimitive(Integer[] nonPrimitive)

Where nonPrimitive is the Integer[] to be converted into the int[].

Share:
36,656
Michael Brenndoerfer
Author by

Michael Brenndoerfer

LinkedIn

Updated on July 09, 2022

Comments

  • Michael Brenndoerfer
    Michael Brenndoerfer almost 2 years

    Is there a fancy way to cast an Integer array to an int array? (I don't want to iterate over each element; I'm looking for an elegant and quick way to write it)

    The other way around I'm using

    scaleTests.add(Arrays.stream(data).boxed().toArray(Double[]::new));

    I'm looking for an one-liner but wasn't able to find something.

    The goal is to:

    int[] valuesPrimitives = <somehow cast> Integer[] valuesWrapper
    
  • Michael Brenndoerfer
    Michael Brenndoerfer almost 9 years
    Hi thanks for the answer. Unfortunately I forgot to mention that I cannot use ArrayUtils. But thanks anyways
  • Marko Topolnik
    Marko Topolnik almost 9 years
    Sometimes I prefer to see mapToInt(i -> i).