Explain Codes LogoExplain Codes Logo

Converting String array to java.util.List

java
arrays
collections
java-8
Alex KataevbyAlex Kataev·Aug 21, 2024
TLDR

Convert a String array to a modifiable List with:

String[] array = {"a", "b", "c"}; // The array party List<String> list = new ArrayList<>(Arrays.asList(array)); // Invites its array friends to the list party

Be cautious of Arrays.asList(), it gives an immutable list. So, we wrap it around with a new ArrayList.

The nuanced tale of Arrays.asList and Collections.addAll

If Arrays.asList(array) is a superhero, it has its quirks. They are as given below:

  • Immutable in nature: Arrays.asList() can't add or remove elements. It's like a party where no new guests can arrive and nobody can leave.
  • Changes are synchronised: Modify the original array, and you'll see changes popping up in the list like unexpected visitors.
String[] array = {"Java", "Python", "C++"}; // Array party guests List<String> list = Arrays.asList(array); // Now they are at the list party array[0] = "JavaScript"; // The controversial guest replacement System.out.println(list); // ["JavaScript", "Python", "C++"] - the list party got the update!

When mutations are a must, use the new ArrayList<>(Arrays.asList(array)) combination, which is like having your party and controlling its guest list. Alternatively, Collections.addAll() is a good option when you have an empty list to control elements individually:

List<String> managedParty = new ArrayList<>(); Collections.addAll(managedParty, array); // Adding array guests one by one to the controlled party

Remember that Arrays.asList() has an O(1) time complexity whereas new ArrayList or Collections.addAll() has an O(n) time complexity where n is the array size.

Alternative approaches and important considerations

Using Streams for Conversion

Introduced in Java 8, the stream API offers an elegant approach for an array to list conversion:

String[] array = {"a", "b", "c"}; List<String> listFromStream = Arrays.stream(array).collect(Collectors.toList()); // Fancy conversion with stream

This approach also opens doors for extra operations such as filter and map.

Maintaining order when converting

Arrays.asList() and Stream API perfectly maintains the order of elements from the array. They are your best bets when order is critical.

Making a separate copy

To avoid changes in the list reflecting on the original array (and vice versa), create a separate copy of the list:

String[] array = {"a", "b", "c"}; List<String> independentList = new ArrayList<>(Arrays.stream(array).collect(Collectors.toList())); // A total clone, Tabula Rasa