我如何转换int[]到列表<整数>在Java?

当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。


当前回答

Arrays.stream(ints).forEach(list::add);

其他回答

下面是一个将数组转换为数组列表的通用方法

<T> ArrayList<T> toArrayList(Object o, Class<T> type){
    ArrayList<T> objects = new ArrayList<>();
    for (int i = 0; i < Array.getLength(o); i++) {
        //noinspection unchecked
        objects.add((T) Array.get(o, i));
    }
    return objects;
}

使用

ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);

这里有一个解决方案:

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));

List<Integer> list = new ArrayList<>();
Collections.addAll(list, iArray);
System.out.println(list);

输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

在Java 8中:

int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());

我将用不同的方法添加另一个答案;没有循环,而是一个匿名类,将利用自动装箱特性:

public List<Integer> asList(final int[] is)
{
    return new AbstractList<Integer>() {
            public Integer get(int i) { return is[i]; }
            public int size() { return is.length; }
    };
}

如果你愿意使用第三方库,这将在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的提交者。