Java Array to List

Java Array to List

Converting array to list in Java

import java.util.Arrays;
import java.util.List;
...
Integer[] sourceArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
List<Integer> intList = Arrays.asList(sourceArray);

But then if you do something like this:

integerList.add(1);

//output:
//Exception in thread "main" java.lang.UnsupportedOperationException

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

Integer[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> integerList = new ArrayList<Integer>(Arrays.asList(values));

Explicit type argument Integer can be replaced with <>

Integer[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> integerList = new ArrayList<>(Arrays.asList(values));

In Java 8 we can use int (primitive type) as well

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
...
int[] values = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> integerList = Arrays.stream(values).boxed().collect(Collectors.toList());
System.out.println(integerList);

//output:
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Converting array to ArrayList in Java

Integer[] values = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ArrayList<Integer> integerArrayList = Arrays.stream(values)
                .collect(Collectors.toCollection(ArrayList::new));