Converting String array to java.util.List
Convert a String array to a modifiable List with:
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.
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:
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:
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:
Was this article helpful?