我试图用下面的代码段将包含整数对象的数组列表转换为原始int[],但它抛出编译时错误。可以在Java中转换吗?
List<Integer> x = new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
我试图用下面的代码段将包含整数对象的数组列表转换为原始int[],但它抛出编译时错误。可以在Java中转换吗?
List<Integer> x = new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
当前回答
Java 8
int[] array = list.stream().mapToInt(i->i).toArray();
OR
int[] array = list.stream().mapToInt(Integer::intValue).toArray();
其他回答
使用Dollar应该非常简单:
List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4
int[] array = $($(list).toArray()).toIntArray();
我计划改进DSL,以删除中间的toArray()调用
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
int[] result = null;
StringBuffer strBuffer = new StringBuffer();
for (Object o : list) {
strBuffer.append(o);
result = new int[] { Integer.parseInt(strBuffer.toString()) };
for (Integer i : result) {
System.out.println(i);
}
strBuffer.delete(0, strBuffer.length());
}
Arrays.setAll ()
List<Integer> x = new ArrayList<>(Arrays.asList(7, 9, 13));
int[] n = new int[x.size()];
Arrays.setAll(n, x::get);
System.out.println("Array of primitive ints: " + Arrays.toString(n));
输出:
原始整数数组:[7,9,13]
这同样适用于long或double类型的数组,但不适用于boolean、char、byte、short或float类型的数组。如果您有一个非常大的列表,甚至可以使用parallelSetAll方法来代替。
对我来说,这是足够好的和优雅的,我不想获得一个外部库或使用流。
文档链接:数组。setAll (int [], IntUnaryOperator)
这对我来说很好:)
网址:https://www.techiedelight.com/convert-list-integer-array-int/
import java.util.Arrays;
import java.util.List;
class ListUtil
{
// Program to convert list of integer to array of int in Java
public static void main(String args[])
{
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] primitive = list.stream()
.mapToInt(Integer::intValue)
.toArray();
System.out.println(Arrays.toString(primitive));
}
}
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);
像正常int[]一样访问arr。