我如何转换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的提交者。

其他回答

也来自番石榴图书馆…com.google.common.primitives.Ints:

List<Integer> Ints.asList(int...)
Arrays.stream(ints).forEach(list::add);

在Java 8+中,可以创建int数组的流。调用任意一个数组。stream或IntStream.of。 调用IntStream#boxed来使用从int原语到Integer对象的装箱转换。 使用流收集到列表中。collect(collections . tolist())。或者更简单地说,在Java 16+中,调用Stream#toList()。

例子:

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

在Java 16及更高版本中:

List<Integer> list = Arrays.stream(ints).boxed().toList();
int[] arr = { 1, 2, 3, 4, 5 };

List<Integer> list = Arrays.stream(arr)     // IntStream
                            .boxed()        // Stream<Integer>
                            .collect(Collectors.toList());

看到这个

那么这个呢:

Int [] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);