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

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


当前回答

如果您使用java 8,我们可以使用流API将其转换为列表。

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

您也可以使用IntStream进行转换。

List<Integer> list = IntStream.of(arr) // return Intstream
                                    .boxed()        // Stream<Integer>
                                    .collect(Collectors.toList());

还有其他外部库,如guava和apache commons 也可以转换它。

欢呼。

其他回答

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

List<Integer> Ints.asList(int...)

在Java 8中使用流:

int[] ints = {1, 2, 3};
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, Arrays.stream(ints).boxed().toArray(Integer[]::new));

或与收藏家

List<Integer> list =  Arrays.stream(ints).boxed().collect(Collectors.toList());

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

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

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

同样值得一看的是这个bug报告,它以“Not a defect”和以下文本结尾:

“自动装箱整个数组不是指定的行为,这是有充分理由的。 对于大型阵列来说,它可能会非常昂贵。”