有没有一种方法可以将整数列表转换为 int 数组(而不是 integer)? 类似于 List 到 int [] 的方式?而不需要循环遍历列表并手动将整数转换为 int。
toArray
方法获取一个由Integers
组成的数组,然后使用apache commons中的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[])
同一主题:
ArrayUtils
。 - gpechetoArray()
之前,为了保证安全,您需要从列表中删除所有的 null 元素。 - Sean Patrick Floyd不需要 :)
你需要遍历这个列表。这应该不会太痛苦。
这是一个实用方法,将整数集合转换为整数数组。如果输入为空,则返回null。如果输入包含任何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);
参考资料:
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())};
我认为这应该解决你的问题