Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

How would I change over int[] into List<Integer> in Java?

Obviously, I'm keen on some other answer than doing it's anything it in a loop, item by item. In any case, if there could be no other answer, I'll pick that one as the best to show the way that this usefulness isn't essential for Java
by

3 Answers

aashaykumar
There is no shortcut for converting from int[] to List<Integer> as Arrays.asList does not deal with boxing and will just create a List<int[]> which is not what you want. You have to make a utility method.

int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>(ints.length);
for (int i : ints)
{
intList.add(i);
}
RoliMishra
In Java 8 you can do this

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
pankajshivnani123
Streams
In Java 8+ you can make a stream of your int array. Call either Arrays.stream or IntStream.of.
Call IntStream#boxed to use boxing conversion from int primitive to Integer objects.
Collect into a list using Stream.collect( Collectors.toList() ). Or more simply in Java 16+, call Stream#toList().
Example:

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());


In Java 16 and later:

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

Login / Signup to Answer the Question.