I need a concise way to create a list of options for testing. Initially, I 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<>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Is there a better way to java arraylist initialize
efficiently?
You can use List.of() if you don’t need a mutable list. This is the cleanest and most efficient option when you only need to read from the list.
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
Why?
- Immutable: This ensures no accidental modifications.
- More performant than
Arrays.asList()
(since List.of()
doesn’t create a fixed-size array).
But: It’s immutable—no add()
or remove()
after initialization.
If you need the list to be mutable, you can combine List.of()
with an ArrayList
to create a modifiable version.
ArrayList<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
Why?
- Concise and clean, yet still mutable.
- No fixed size limitations like
Arrays.asList()
.
But: Slightly more overhead than a plain ArrayList
initialization, but this is rarely an issue unless you’re doing heavy processing.
If your list needs to undergo some dynamic processing or transformation, using Streams can be a powerful approach for initializing your java arraylist initialize
.
ArrayList<String> places = new ArrayList<>(
Stream.of("Buenos Aires", "Córdoba", "La Plata")
.collect(Collectors.toList())
);
Why?
- Ideal if you need to perform filtering, mapping, or other transformations right when initializing the list.
- Powerful and flexible for more complex use cases.
But: Overkill for static, simple lists. If you’re just initializing with hardcoded values, this might be more complexity than needed.