Reputation: 4769
What is the most efficient (performant) way to create a list with just one element?
Upvotes: 6
Views: 220
Reputation: 21122
As an alternative to Collections.singletonList(T o)
mentioned in other answers, there's List.of(E e1)
. This is the single-element overload of the unmodifiable lists static factory methods, which create unmodifiable lists of arbitrary sizes.
While the current implementation has a small bit of additional overhead compared to singletonList
, it is likely to be similarly performant to singletonList
in practice.
Upvotes: 0
Reputation: 359826
Just use:
Collections#singletonList()
, which returns a List
, orCollections#singleton()
, which returns a Set
.Upvotes: 8