Is there a Utility method somewhere that can do this in 1 line? I can't find it anywhere in Collections
, or List
.
public List<String> stringToOneElementList(String s) {
List<String> list = new ArrayList<String>();
list.add(s);
return list;
}
I don't want to re-invent the wheel unless I plan on putting fancy rims on it.
Well... the type can be T
, and not String
. but you get the point. (with all the null checking, safety checks...etc)
This question is related to
java
arraylist
collections
Yet another alternative is double brace initialization, e.g.
new ArrayList<String>() {{ add(s); }};
but it is inefficient and obscure. Therefore only suitable:
With Java 8 Streams:
Stream.of(object).collect(Collectors.toList())
or if you need a set:
Stream.of(object).collect(Collectors.toSet())
Collections.singletonList(object)
the list created by this method is immutable.
You can use the utility method Arrays.asList
and feed that result into a new ArrayList
.
List<String> list = new ArrayList<String>(Arrays.asList(s));
Other options:
List<String> list = new ArrayList<String>(Collections.nCopies(1, s));
and
List<String> list = new ArrayList<String>(Collections.singletonList(s));
ArrayList(Collection)
constructor.Arrays.asList
method.Collections.nCopies
method.Collections.singletonList
method.With Java 7+, you may use the "diamond operator", replacing new ArrayList<String>(...)
with new ArrayList<>(...)
.
Java 9
If you're using Java 9+, you can use the List.of
method:
List<String> list = new ArrayList<>(List.of(s));
Regardless of the use of each option above, you may choose not to use the new ArrayList<>()
wrapper if you don't need your list to be mutable.
Seeing as Guava gets a mention, I thought I would also suggest Eclipse Collections (formerly known as GS Collections).
The following examples all return a List
with a single item.
Lists.mutable.of("Just one item");
Lists.mutable.with("Or use with");
Lists.immutable.of("Maybe it must be immutable?");
Lists.immutable.with("And use with if you want");
There are similar methods for other collections.
The other answers all use Arrays.asList()
, which returns an unmodifiable list (an UnsupportedOperationException
is thrown if you try to add or remove an element). To get a mutable list you can wrap the returned list in a new ArrayList
as a couple of answers point out, but a cleaner solution is to use Guava's Lists.newArrayList() (available since at least Guava 10, released in 2011).
For example:
Lists.newArrayList("Blargle!");
Very simply:
Arrays.asList("Hi!")
Source: Stackoverflow.com