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

后端 未结 5 2017
春和景丽
春和景丽 2020-12-02 17:01

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)

T

相关标签:
5条回答
  • 2020-12-02 17:34

    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.

    0 讨论(0)
  • 2020-12-02 17:36

    You can use Stream APIs of Java 8

    int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();
    
    0 讨论(0)
  • 2020-12-02 17:37

    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>
    
    0 讨论(0)
  • 2020-12-02 17:44

    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);

    0 讨论(0)
  • 2020-12-02 17:50

    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[].

    0 讨论(0)
提交回复
热议问题