如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:02:52  来源:igfitidea点击:

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

javaarraysjava-8wrapper

提问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.lang3jar file which provides ArrayUtilsclass.
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 nonPrimitiveis the Integer[]to be converted into the int[].

哪里nonPrimitiveInteger[]要转换成int[]