简体   繁体   中英

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

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

您可以使用 Java 8 的 Stream API

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

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.

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>

如果您有权访问 Apache lang 库,那么您可以使用 ArrayUtils.toPrimitive(Integer[]) 方法,如下所示:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM