Converting array to list in Java
This question explores different ways to transform arrays into lists in Java using methods like Arrays.asList() and List.of(), along with tips on mutability and common pitfalls.
Converting an array to a list in Java is a pretty common task—especially when you want the flexibility of a list (like dynamic resizing or using collection methods) instead of a fixed-size array. Java provides a few straightforward ways to do this.
1. Using Arrays.asList()
This is the most popular method:
import java.util.Arrays;
import java.util.List;
String[] array = {"apple", "banana", "cherry"};
List list = Arrays.asList(array);
- Pros: Quick and easy.
- Cons: Returns a fixed-size list backed by the array—so you can’t add or remove elements.
2. Creating a Mutable List
If you want to modify the list (add/remove items), wrap it in a new ArrayList:
List modifiableList = new ArrayList<>(Arrays.asList(array));
3. Using Java 8+ Streams
For more flexibility or if you're already using streams:
List list = Arrays.stream(array).collect(Collectors.toList());
Especially useful for filtering or transforming elements as you convert.
4. Java 9+ with List.of()
List list = List.of(array);
Creates an immutable list (cannot be changed).
So depending on whether you want a mutable or immutable list, and what version of Java you’re using, you’ve got options. For most everyday use cases, new ArrayList<>(Arrays.asList(array)) is the safest bet!