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

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


当前回答

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

<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[]转换为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);
}

你可以使用IntStream of并在使用reverseOrder比较器排序后将其装箱为Integer。

List<Integer> listItems = IntStream.of(arrayItems)
                .boxed()
                .sorted(Collections.reverseOrder())
                .collect(Collectors.toList());

这种方法的优点是更加灵活,因为您可以使用不同的收集器来创建不同类型的列表(例如,ArrayList, LinkedList等)。

   /* Integer[] to List<Integer> */



        Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        List<Integer> arrList = new ArrayList<>();
        arrList.addAll(Arrays.asList(intArr));
        System.out.println(arrList);


/* Integer[] to Collection<Integer> */


    Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
    Collection<Integer> c = Arrays.asList(intArr);

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

<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[] arr = { 1, 2, 3, 4, 5 };

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

看到这个