Converting array to list in Java Converting array to list in Java java java

Converting array to list in Java


In your example, it is because you can't have a List of a primitive type. In other words, List<int> is not possible.

You can, however, have a List<Integer> using the Integer class that wraps the int primitive. Convert your array to a List with the Arrays.asList utility method.

Integer[] spam = new Integer[] { 1, 2, 3 };List<Integer> list = Arrays.asList(spam);

See this code run live at IdeOne.com.


In Java 8, you can use streams:

int[] spam = new int[] { 1, 2, 3 };Arrays.stream(spam)      .boxed()      .collect(Collectors.toList());


Speaking about conversion way, it depends on why do you need your List.If you need it just to read data. OK, here you go:

Integer[] values = { 1, 3, 7 };List<Integer> list = Arrays.asList(values);

But then if you do something like this:

list.add(1);

you get java.lang.UnsupportedOperationException.So for some cases you even need this:

Integer[] values = { 1, 3, 7 };List<Integer> list = new ArrayList<Integer>(Arrays.asList(values));

First approach actually does not convert array but 'represents' it like a List. But array is under the hood with all its properties like fixed number of elements. Please note you need to specify type when constructing ArrayList.