How to quickly and conveniently create a one element arraylist
Get your hands on a mutable ArrayList
with just one component by pairing the ArrayList
constructor with Collections.singletonList()
.
This simple one-liner pops out a fully mutable, single-item list just waiting to grow.
Quick ways to generate singleton lists
Immutable list using Collections.singletonList()
Need a list that's set in stone? Use the Collections.singletonList()
method for a quick, immutable list:
Java 9 List.of()
method for immutable list
In Java 9 and onwards, you can use the List.of()
method for a nice one-item immutable list:
Create list using Stream API
Java's Stream API allows you to create collections in a more functional style:
Google's Guava library approach
The Guava library from Google gives us Lists.newArrayList()
, an elegant method to create a mutable list:
Digging deeper: Other singleton collection options
Stream API beyond just Lists
We are not only restricted to Lists. Say hello to Sets! A Set
with single element:
Multiplying your one element
For those rare situations where you need multiple copies of the same element in a list, Java has you covered with Collections.nCopies
:
Mutable, Immutable or fixed-size?
Different methods yield different types of collections:
Collections.singletonList()
generates an immutable list.Arrays.asList()
produces a fixed-size list.- Wrapping with
new ArrayList<>()
bestows mutability.
Watch your step!
IDE might not be your savior
Your IDE might be a lifesaver, but it won't always warn you about single-element asList
calls. Stick to Collections.singletonList()
for clarity.
Respect immutability
Caught yourself transforming asList()
into new ArrayList<>()
? Stop right there if you truly respect immutability.
A fair warning about type safety
Java Generics and <>
exist for a reason. Harness their potential for type safety:
Pro tips for power users
Third-party libraries: An ocean of opportunities
Java's standard library is vast, but third-party libraries like Guava can serve as a treasure trove of handy utilities.
Battling overloads
Methods such as Arrays.asList()
and List.of()
are loaded with overloads. Know their role and use them wisely, especially for single-element collections.
The ever-evolving Java
Keep a lookout for the upcoming enhancements in Java. Singleton collections might get even simpler and faster.
Was this article helpful?