如何快速方便地创建一个单元素数组列表

是否有一个实用方法,可以在1行完成这个?我在CollectionsList中找不到它。

public List<String> stringToOneElementList(String s) {
List<String> list = new ArrayList<String>();
list.add(s);
return list;
}

我不想重新发明轮子,除非我打算把花哨的轮辋上。

嗯…类型可以是T,而不是String。但你懂的。(所有的空检查,安全检查…等)

402130 次浏览

非常简单:

Arrays.asList("Hi!")

固定大小List

我所知道的最简单的方法是用Arrays.asList(T...)创建一个固定大小的单个元素List

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

变量大小List

如果它的大小需要变化,你可以构造一个ArrayList和固定的size__abc1

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

并且(在Java 7+中)你可以使用diamond操作符<>来创建它

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

单元素列表

集合可以返回一个包含单个元素且list为不可变的列表:

Collections.singletonList(s)

这样做的好处是ide代码分析不会对单个元素的asList(..)调用发出警告。

你可以使用实用程序方法Arrays.asList并将结果提供给一个新的ArrayList

List<String> list = new ArrayList<String>(Arrays.asList(s));

其他选项:

List<String> list = new ArrayList<String>(Collections.nCopies(1, s));

而且

List<String> list = new ArrayList<String>(Collections.singletonList(s));

在Java 7+中,你可以使用“菱形操作符”,用new ArrayList<>(...)替换new ArrayList<String>(...)

Java 9

如果你使用Java 9+,你可以使用List.of方法:

List<String> list = new ArrayList<>(List.of(s));

不管使用上述每个选项,如果你不需要你的列表是可变的,你可以选择不使用new ArrayList<>()包装器。

其他答案都使用Arrays.asList(),它返回一个不可修改的列表(如果您试图添加或删除一个元素,则抛出UnsupportedOperationException)。要获得一个可变列表,你可以将返回的列表包装在一个新的ArrayList中,但一个更干净的解决方案是使用番石榴的 Lists.newArrayList ()(至少从2011年发布的番石榴10开始可用)。

例如:

Lists.newArrayList("Blargle!");

还有另一种选择是双大括号初始化,例如:

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

它既低效又晦涩。因此只适合:

  • 在不介意内存泄漏的代码中,例如大多数单元测试和其他短期程序;
  • 如果其他的解决方案都不适用,我认为这意味着你已经一直向下滚动到这里,寻找填充一个不同类型的容器,而不是问题中的数组列表。
Collections.singletonList(object)

此方法创建的列表是不可变的。

使用Java 8流:

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

或者如果你需要一组:

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

鉴于番石榴被提到,我想我也会建议Eclipse集合(以前称为GS Collections)。

下面的例子都返回带有单个项的List

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

其他集合也有类似的方法。