Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to convert an array to a list and back

Short answer

For a modifiable list wrap the array in new ArrayList<>(...), and go back with toArray():

void main() {
    String[] array = {"red", "green", "blue"};
 
    List<String> list = new ArrayList<>(Arrays.asList(array));
    list.add("black");
 
    String[] back = list.toArray(new String[0]);
    IO.println(list);
    IO.println(back.length);
}

Output:

[red, green, blue, black]
4

Read-only

List.of(array) creates an unmodifiable copy — good when you only need to read the list:

void main() {
    String[] array = {"a", "b"};
    List<String> list = List.of(array);
 
    IO.println(list);
}

Output:

[a, b]

Arrays.asList is a view of the array

Arrays.asList() does not copy the data: the list and the array are linked. You can change elements, but not the size:

void main() {
    String[] array = {"a", "b", "c"};
    List<String> view = Arrays.asList(array);
 
    view.set(0, "z");
    IO.println(array[0]);
}

Output:

z

A primitive array

Arrays.asList(int[]) does not work as expected — use a stream for int[]:

void main() {
    int[] numbers = {3, 1, 2};
 
    List<Integer> list = Arrays.stream(numbers).boxed().toList();
    int[] back = list.stream().mapToInt(Integer::intValue).toArray();
 
    IO.println(list);
    IO.println(Arrays.toString(back));
}

Output:

[3, 1, 2]
[3, 1, 2]

Common mistake

Adding an element to a list from Arrays.asList() or List.of(). Their size is fixed:

void main() {
    List<String> list = Arrays.asList("a", "b");
    list.add("c");
}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException

If you need to change the list, make a copy: new ArrayList<>(Arrays.asList(...)).

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.