我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
当前回答
如果你愿意使用第三方库,这将在Eclipse Collections中工作:
int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);
注意:我是Eclipse Collections的提交者。
其他回答
如果你愿意使用第三方库,这将在Eclipse Collections中工作:
int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);
注意:我是Eclipse Collections的提交者。
数组。asList将不会像其他一些答案所期望的那样工作。
这段代码不会创建一个包含10个整数的列表。它将输出1,而不是10:
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List lst = Arrays.asList(arr);
System.out.println(lst.size());
这将创建一个整数列表:
List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
如果你已经有了整型数组,没有快速转换的方法,最好使用循环。
另一方面,如果数组中有对象,而不是原语,则为数组。asList将工作:
String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);
那么这个呢:
Int [] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);
下面是另一种可能性,同样是Java 8流:
void intArrayToListOfIntegers(int[] arr, List<Integer> list) {
IntStream.range(0, arr.length).forEach(i -> list.add(arr[i]));
}
没有将int[]转换为List<Integer>作为数组的快捷方式。asList不处理装箱,只会创建一个List<int[]>,这不是你想要的。你必须创建一个实用方法。
int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>(ints.length);
for (int i : ints)
{
intList.add(i);
}