How to convert int[] into List in Java?

2018-12-31 12:58发布

How do I convert int[] into List<Integer> in Java?

Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as the best to show the fact that this functionality is not part of Java.

17条回答
人间绝色
2楼-- · 2018-12-31 13:29

Here is a generic way to convert array to ArrayList

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

Usage

ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);
查看更多
泪湿衣
3楼-- · 2018-12-31 13:31

Also from guava libraries... com.google.common.primitives.Ints:

List<Integer> Ints.asList(int...)
查看更多
牵手、夕阳
4楼-- · 2018-12-31 13:31

I'll add another answer with a different method; no loop but an anonymous class that will utilize the autoboxing features:

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; }
    };
}
查看更多
栀子花@的思念
5楼-- · 2018-12-31 13:32

In Java 8 with stream:

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

or with Collectors

List<Integer> list =  Arrays.stream(ints).boxed().collect(Collectors.toList());
查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 13:32

If you're open to using a third party library, this will work in 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);

Note: I am a committer for Eclipse Collections.

查看更多
公子世无双
7楼-- · 2018-12-31 13:33

Here is a solution:

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

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
查看更多
登录 后发表回答