Overview
In this tutorial, we show you how to convert int array to List in
Java. We using core Java libraries, Java 8 Stream API, Apache Commons Lang and Google Guava.
Using For-each loop
package com.jackrutorial;
import java.util.ArrayList;
import java.util.List;
public class ConvertArrayToListExample1 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4 , 5, 6, 7, 8, 9};
List<Integer> listNumber = new ArrayList<Integer>();
for(int i : arr) {
listNumber.add(i);
}
System.out.println("ArrayList: " + listNumber);
}
}
Output
ArrayList: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using Java 8 Stream API
package com.jackrutorial;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ConvertArrayToListExample2 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4 , 5, 6, 7, 8, 9};
List<Integer> listNumber = new ArrayList<Integer>();
listNumber = Arrays.stream(arr).boxed().collect(Collectors.toList());
System.out.println("ArrayList: " + listNumber);
}
}
Output
ArrayList: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using Apache Commons Lang - Arrays.asList & ArrayUtils.toObject
Add commons-lang3-3.8.1.jar lib to your project. Then Using Arrays.asList() and ArrayUtils.toObject()
package com.jackrutorial;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
public class ConvertArrayToListExample3 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4 , 5, 6, 7, 8, 9};
List<Integer> listNumber = new ArrayList<Integer>();
listNumber = Arrays.asList(ArrayUtils.toObject(arr));
System.out.println("ArrayList: " + listNumber);
}
}
Output
ArrayList: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using Google Guava with method Ints.asList
Add guava-27.1-jre.jar lib to your project. Then using Ints asList() function. Guava's Ints.asList() returns a fixed-size list backed by the specified array.
package com.jackrutorial;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
public class ConvertArrayToListExample3 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4 , 5, 6, 7, 8, 9};
List<Integer> listNumber = new ArrayList<Integer>();
listNumber = Arrays.asList(ArrayUtils.toObject(arr));
System.out.println("ArrayList: " + listNumber);
}
}
Output
ArrayList: [1, 2, 3, 4, 5, 6, 7, 8, 9]