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.
Streams
In Java 8 you can do this
give a try to this class:
testcase:
What about this:
int[] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);
Arrays.asList will not work as some of the other answers expect.
This code will not create a list of 10 integers. It will print 1, not 10:
This will create a list of integers:
If you already have the array of ints, there is not quick way to convert, you're better off with the loop.
On the other hand, if your array has Objects, not primitives in it, Arrays.asList will work:
In Java 8 :