Initialization of an ArrayList in one line
Effortlessly initialize an ArrayList with Arrays.asList
for a modifiable collection such as:
Post Java 9? Opt for List.of
for an immutable list and then wrap it in an ArrayList for mutability:
Offering both List.of
for efficiency and Arrays.asList
for legacy Java versions.
List vs ArrayList: Making the right choice
When it comes to a dilemma between List and ArrayList, make a wise choice of coding to interfaces. This practice paves the path to a more resilient and maintainable code:
Tackling the special cases
Single item lists
When your list needs only one element, go for:
Immutable lists
Does your list not need changes? An immutable list is the way to go. Need to alter things later? Make a mutable copy:
Using Stream API for collections
Put the power of the Stream API in your hands for flexible collection manipulation:
Efficient addition of elements
Rather than adding elements one by one, save time and add multiple elements:
Going the extra mile
The power of interfaces
The strength of Java lies in its interfaces. When you don't need to use specific ArrayList features, it's advisable to declare your type as List for flexibility:
Supplement with third-party libraries
Consider Google Guava's utility method for ArrayList creation and enjoy the clean syntax:
Java 16 and above
If you're using Java 16 and above, the toList()
method on Stream provides a one-liner syntax for converting stream to list:
Null values and lists
Watch out for nulls
! They continue to be the Achilles heel in your lists:
List.of
andStream.toList()
: exclude null elements.Arrays.asList
: null friendly.
Was this article helpful?