There are many ways to convert an array to a list in Java. In this tutorial, we will cover the following:
- Using the Arrays.asList() method
- Using Java 8 Streams API
- Using the List.of() method
Convert array to list in Java using the Arrays.asList() method
We can use the asList() method from the Arrays class, which belongs to java.util package. The asList() method returns a fixed-size list backed by the specified array.
Example
class Test { public static void main(String[] args) throws IOException { String[] array = new String[]{"Steve", "Tom", "Megan", "Melissa", "Ryan"}; List<String> list = Arrays.asList(array); System.out.println(list); } }
Output: [Steve, Tom, Megan, Melissa, Ryan]
Using the Java 8 Streams API
There is a way to convert an array to a list using the Streams API.
Example
class Test { public static void main(String[] args) throws IOException { int[] intArray = new int[]{1, 2, 3, 4, 5}; String[] stringArray = new String[]{"Steve", "Tom", "Megan", "Melissa", "Ryan"}; // when converting an int array, we need to put the boxed() operation in a stream to convert ints to Integers List<Integer> integerList = Arrays.stream(intArray).boxed().collect(Collectors.toList()); List<String> stringList = Arrays.stream(stringArray).collect(Collectors.toList()); System.out.println(integerList); System.out.println(stringList); } }
Output: [1, 2, 3, 4, 5] [Steve, Tom, Megan, Melissa, Ryan]
In case you need an ArrayList, use the following code:
ArrayList<String> stringList = Arrays.stream(stringArray).collect(Collectors.toCollection(ArrayList::new));
Using the List.of() method
There is also a List.of() method introduced in Java 9 that returns an unmodifiable list.
Example
class Test { public static void main(String[] args) throws IOException { String[] array = new String[]{"Steve", "Tom", "Megan", "Melissa", "Ryan"}; List<String> namesList = List.of(array); System.out.println(namesList); } }
Output: [Steve, Tom, Megan, Melissa, Ryan]
That’s it.
Happy coding!