How to quickly and conveniently create a one element arraylist

JavaArraylistCollections

Java Problem Overview


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)

Java Solutions


Solution 1 - Java

###Fixed size List The easiest way, that I know of, is to create a fixed-size single element List with Arrays.asList(T...) like

// Returns a List backed by a varargs T.
return Arrays.asList(s);

###Variable size List If it needs vary in size you can construct an ArrayList and the fixed-sizeList like

return new ArrayList<String>(Arrays.asList(s));

and (in Java 7+) you can use the diamond operator <> to make it

return new ArrayList<>(Arrays.asList(s));

###Single Element List Collections can return a list with a single element with list being immutable:

Collections.singletonList(s)

The benefit here is IDEs code analysis doesn't warn about single element asList(..) calls.

Solution 2 - Java

Collections.singletonList(object)

the list created by this method is immutable.

Solution 3 - Java

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));

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.

Solution 4 - Java

With Java 8 Streams:

Stream.of(object).collect(Collectors.toList())

or if you need a set:

Stream.of(object).collect(Collectors.toSet())

Solution 5 - Java

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!");

Solution 6 - Java

Very simply:

Arrays.asList("Hi!")

Solution 7 - Java

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.

Solution 8 - Java

Yet another alternative is double brace initialization, e.g.

new ArrayList<String>() {{ add(s); }};

but it is inefficient and obscure. Therefore only suitable:

  • in code that doesn't mind memory leaks, such as most unit tests and other short-lived programs;
  • and if none of the other solutions apply, which I think implies you've scrolled all the way down here looking to populate a different type of container than the ArrayList in the question.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid T.View Question on Stackoverflow
Solution 1 - JavaElliott FrischView Answer on Stackoverflow
Solution 2 - JavaAndrewView Answer on Stackoverflow
Solution 3 - JavargettmanView Answer on Stackoverflow
Solution 4 - JavaMarko JurisicView Answer on Stackoverflow
Solution 5 - Javauser167019View Answer on Stackoverflow
Solution 6 - JavaSLaksView Answer on Stackoverflow
Solution 7 - Javavegemite4meView Answer on Stackoverflow
Solution 8 - JavaSteinView Answer on Stackoverflow