1. Introduction
In this article we will see how to convert an array i.e. primitive and object array to List. The following methods acts as a bridge between array and Collection.
2. How to convert array to List?
The 4 ways we are planning to convert the array to List are as follows:
- For-each loop on array
- Primitive stream
- Arrays.asList
- Stream
2.1 int[] array to List<Integer> using for-each loop
We can iterate over the array elements and insert them into the List.
int[] arr = { 1, 2, 3, 4, 5 }; List<Integer> numbers = new ArrayList<>(); for (int val : arr) { numbers.add(Integer.valueOf(val)); // No autoboxing } Assert.assertEquals(Arrays.asList(1, 2, 3, 4, 5), numbers);
2.2 int[] array to List<Integer> using IntStream
IntStream was added to Java 8 to work declaratively on int elements. Below example converts the int[] to List.
int[] arr = { 1, 2, 3, 4, 5 }; List<Integer> numbers = IntStream.of(arr) .mapToObj(Integer::valueOf) .collect(Collectors.toList()); Assert.assertEquals(Arrays.asList(1, 2, 3, 4, 5), numbers);
2.3 Integer[] to List<Integer> using Arrays.asList loop
In this example we use a reference array or object array to convert it to List. We can directly we asList method of Arrays class to convert it to List.
Integer[] arr = { 1, 2, 3, 4, 5 }; List<Integer> numbers = Arrays.asList(arr);
2.4 Integer[] to List<Integer> using Arrays.stream
To convert the object array to List we use Arrays.stream method.
Integer[] arr = { 1, 2, 3, 4, 5 }; List<Integer> numbers = Arrays.stream(arr).collect(Collectors.toList());
3. Conclusion
In this article, we saw few different ways to convert array to List. This article determines how to establish a bridge between array and Collection.