有没有办法将整数列表转换为整数数组(不是整数)。像List to int []之类的东西?不循环遍历列表并手动将intger转换为int。
答案 0 :(得分:41)
您可以使用toArray
从apache commons获取Integers
,ArrayUtils
数组,将其转换为int[]
。
List<Integer> integerList = new ArrayList<Integer>();
Integer[] integerArray = integerList.toArray(new Integer[0]);
int[] intArray = ArrayUtils.toPrimitive(integerArray);
资源:
ArrayUtils.toPrimitive(Integer[])
Collection.toArray(T[])
关于同一主题:
答案 1 :(得分:3)
我确信你可以在第三方库中找到一些东西,但我不相信Java标准库中有任何东西。
我建议您只编写一个实用程序函数来执行此操作,除非您需要许多类似的功能(在这种情况下,值得查找相关的第三方库)。请注意,您需要弄清楚如何处理列表中的空引用,这显然无法在int数组中准确表示。
答案 2 :(得分:1)
不:)
您需要遍历列表。它应该不会太痛苦。
答案 3 :(得分:1)
这是一个将整数集合转换为整数数组的实用程序方法。如果输入为null,则返回null。如果输入包含任何空值,则会创建防御副本,从中剥离所有空值。原始集合保持不变。
public static int[] toIntArray(final Collection<Integer> data){
int[] result;
// null result for null input
if(data == null){
result = null;
// empty array for empty collection
} else if(data.isEmpty()){
result = new int[0];
} else{
final Collection<Integer> effective;
// if data contains null make defensive copy
// and remove null values
if(data.contains(null)){
effective = new ArrayList<Integer>(data);
while(effective.remove(null)){}
// otherwise use original collection
}else{
effective = data;
}
result = new int[effective.size()];
int offset = 0;
// store values
for(final Integer i : effective){
result[offset++] = i.intValue();
}
}
return result;
}
更新: Guava具有此功能的一行代码:
int[] array = Ints.toArray(data);
<强>参考:
答案 4 :(得分:-3)
List<Integer> listInt = new ArrayList<Integer>();
StringBuffer strBuffer = new StringBuffer();
for(Object o:listInt){
strBuffer.append(o);
}
int [] arrayInt = new int[]{Integer.parseInt(strBuffer.toString())};
我认为这应该可以解决你的问题