How do I convert int[]
into List
in Java?
Of course, I\'m interested in any other answer than doing it in a loop, item by it
In Java 8 :
int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
If you are using java 8, we can use the stream API to convert it into a list.
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
You can also use the IntStream to convert as well.
List<Integer> list = IntStream.of(arr) // return Intstream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
There are other external library like guava and apache commons also available convert it.
cheers.
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);
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);
}
It's also worth checking out this bug report, which was closed with reason "Not a defect" and the following text:
"Autoboxing of entire arrays is not specified behavior, for good reason. It can be prohibitively expensive for large arrays."
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]