如何在 Java 中将 Integer[] 转换为 int[] 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31394715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Integer[] to int[] array in Java?
提问by Michael
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)
有没有一种奇特的方法可以将 Integer 数组转换为 int 数组?(我不想遍历每个元素;我正在寻找一种优雅而快速的编写方式)
The other way around I'm using
我正在使用的另一种方式
scaleTests.add(Arrays.stream(data).boxed().toArray(Double[]::new));
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
采纳答案by Vaibhav
You can use Stream APIs of Java 8
您可以使用 Java 8 的 Stream API
int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();
回答by Juned Ahsan
If you can consider using Apache commons ArrayUtilsthen there is a simple toPrimitiveAPI:
如果您可以考虑使用Apache commons ArrayUtils,那么有一个简单的toPrimitiveAPI:
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.
public static double[] toPrimitive(Double[] array, double valueForNull)
将对象 Doubles 数组转换为处理 null 的基元。此方法为空输入数组返回空值。
回答by Janin
Using Guava, you can do the following:
使用番石榴,您可以执行以下操作:
int[] intArray = Ints.toArray(intList);
If you're using Maven, add this dependency:
如果您使用的是 Maven,请添加此依赖项:
<dependency>
<groudId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
回答by Ant?nio Sérgio Ferraz
If you have access to the Apache lang library, then you can use the ArrayUtils.toPrimitive(Integer[]) method like this:
如果您有权访问 Apache lang 库,那么您可以使用 ArrayUtils.toPrimitive(Integer[]) 方法,如下所示:
int[] primitiveArray = ArrayUtils.toPrimitive(objectArray);
int[] primitiveArray = ArrayUtils.toPrimitive(objectArray);
回答by Shekhar
You can download the org.apache.commons.lang3
jar file which provides ArrayUtils
class.
Using the below line of code will solve the problem:
您可以下载org.apache.commons.lang3
提供ArrayUtils
类的jar 文件。
使用以下代码行将解决问题:
ArrayUtils.toPrimitive(Integer[] nonPrimitive)
ArrayUtils.toPrimitive(Integer[] nonPrimitive)
Where nonPrimitive
is the Integer[]
to be converted into the int[]
.
哪里nonPrimitive
是Integer[]
要转换成int[]
。