How To Convert A Primitive Array To List In Java
Posted By : Sanjay Saini | 26-Jan-2018
Hi guys,
In this blog.I will be going to explain to you how to convert a primitive data type array to List. we are taking a primitive array of int for explaining the ways.
Before Java 8, It was compulsory to iterate over array to convert into the List but In Java 8 we are easily doing this and didn't need looping over array.
Sample Code to change a primitive array int[] to a List.
package com.sanjay;
import java.util.ArrayList;
import java.util.List;
public class ConverPrimitiveArrayToList {
public static void main(String[] args) {
int[] intArray = {10,11,12,13,14,15,16,17,18,19,20};
List<Integer> integerArrayList = convertPrimitiveArrayToList(intArray);
System.out.println("Array List : " + integerArrayList);
}
private static List convertPrimitiveArrayToList(int[] intArray) {
List<Integer> integerArrayList = new ArrayList<>();
for (int i : intArray) {
integerArrayList.add(i);
}
return integerArrayList;
}
}
Now we will discuss how to do this In java 8 :
Java 8 has introduced a new feature i.e Streams API and with the help of Streams API, we can do many things easily. Code Sample of Java 8 :
package com.sanjay;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ConverPrimitiveArrayToList {
public static void main(String[] args) {
int[] intArray = {10,11,12,13,14,15,16,17,18,19,20};
List<Integer> integerArrayList = Arrays.stream(intArray).boxed().collect(Collectors.toList());
System.out.println("integerArrayList : " + integerArrayList);
}
}
Note : You can’t use the most popular Arrays.asList to convert it directly, because boxing issue.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sanjay Saini
Sanjay has been working on web application development using frameworks like Java, groovy and grails. He loves listening to music , playing games and going out with friends in free time.