2010-09-14 49 views
12

是否有办法将整数列表转换为整数列(不是整数)。像列表int []?没有循环遍历列表并手动将intger转换为int。将整数列表转换为int数组

+0

循环这里有什么问题? – 2010-09-14 12:12:11

回答

3

我确定你可以在第三方库中找到某些东西,但我不相信Java标准库中内置了任何东西。

我建议你只是写一个实用函数来做到这一点,除非你需要很多类似的功能(在这种情况下,它是值得找到相关的第三方库)。请注意,您需要弄清楚如何处理列表中的空引用,这显然无法在int数组中精确表示。

+1

@Downvoter:关心评论? – 2011-02-24 08:01:35

1

否:)

您需要遍历列表。它不应该太痛苦。

40

您可以使用toArray从apache commons中获取Integers,ArrayUtils的数组,以将其转换为int[]


List<Integer> integerList = new ArrayList<Integer>(); 
Integer[] integerArray = integerList.toArray(new Integer[0]); 
int[] intArray = ArrayUtils.toPrimitive(integerArray); 

资源:

上的同一主题:

+0

+1,即将张贴相同。 :-) – missingfaktor 2010-09-14 06:17:00

+0

有一个错字,它应该是'ArrayUtils'。 – gpeche 2010-09-14 06:39:01

+0

你是对的,谢谢。 – 2010-09-14 06:41:33

1

下面是整数的集合转换为整数的阵列的实用程序方法。如果输入为空,则返回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); 

参考:

-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())}; 

我认为这应该可以解决你的问题