What is the best way to initialize an ArrayList in Java in a single line?
I needed a list of options for testing, so I initially wrote:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
Then, I refactored it to:
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Is there a more efficient way to initialize an ArrayList in Java while keeping it concise?
You already discovered one of the best ways to initialize an ArrayList in Java in a single line:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Why use this?
Concise and readable: Creates a mutable ArrayList that allows adding/removing elements later.
Potential drawback?
If you use*List places = Arrays.asList(…) without wrapping it in an ArrayList, the list becomes fixed-size, meaning add() or remove() will throw an exception.
If you don’t need to modify the list, Java 9 introduced List.of(), which is even more efficient:
List places = List.of(“Buenos Aires”, “Córdoba”, “La Plata”);
Why use this?
Shorter and cleaner than Arrays.asList().
Immutable—ensures the list remains constant.
More efficient since Java optimizes List.of() for performance.
When not to use?
If you plan to modify the list, use an ArrayList instead.
If you want a dynamic list initialization, you can leverage Java Streams:
ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata")
.collect(Collectors.toCollection(ArrayList::new));
Why use this?
More flexible—allows pre-processing (e.g., filtering, mapping) before collecting into a list.
Still results in a modifiable ArrayList.
When to use?
If you need extra processing before creating the list (e.g., converting elements, filtering duplicates).