在java中初始化字符串列表的最短方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6520382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:35:43  来源:igfitidea点击:

What is the shortest way to initialize List of strings in java?

javaarraysstringlistinitialization

提问by Vladimir

I am searching for the shortest way (in code) to initialize list of strings and array of strings, i.e. list/array containing "s1", "s2", "s3" string elements.

我正在寻找最短的方法(在代码中)来初始化字符串列表和字符串数组,即包含“s1”、“s2”、“s3”字符串元素的列表/数组。

采纳答案by Jon Skeet

There are various options. Personally I like using Guava:

有多种选择。我个人喜欢使用番石榴

List<String> strings = Lists.newArrayList("s1", "s2", "s3");

(Guava's a library worth having anyway, of course :)

(当然,番石榴是一个值得拥有的图书馆:)

Using just the JDK, you could use:

仅使用 JDK,您可以使用:

List<String> strings = Arrays.asList("s1", "s2", "s3");

Note that this will return an ArrayList, but that's notthe normal java.util.ArrayList- it's an internal one which is mutable but fixed-size.

请注意,这将返回一个ArrayList,但这不是正常的java.util.ArrayList- 它是一个内部的,可变但大小固定。

Personally I prefer the Guava version as it makes it clear what's going on (the list implementation which will be returned). It's also stillclear what's going on if you statically import the method:

我个人更喜欢 Guava 版本,因为它清楚地说明了正在发生的事情(将返回的列表实现)。如果您静态导入该方法,也清楚发生了什么:

// import static com.google.common.collect.Lists.newArrayList;
List<String> strings = newArrayList("s1", "s2", "s3");

... whereas if you statically import asListit looks a little odder.

...而如果你静态导入asList它看起来有点奇怪。

Another Guava option, if you don't want a modifiable-in-any-way list:

另一个番石榴选项,如果你不想要一个以任何方式修改的列表:

ImmutableList<String> strings = ImmutableList.of("s1", "s2", "s3");

I typically want to eitherhave a completely mutable list (in which case Lists.newArrayListis best) ora completely immutable list (in which case ImmutableList.ofis best). It's rare that I really wanta mutable-but-fixed-size list.

通常我想要么有一个完全可变的列表(在这种情况下Lists.newArrayList是最好的),完全不可变列表(在这种情况下ImmutableList.of是最好的)。我很少真正想要一个可变但固定大小的列表。

回答by Buhake Sindi

List<String> stringList = Arrays.asList("s1", "s2", "s3");

All these objects exists in the JDK.

所有这些对象都存在于 JDK 中。

PS:As aioobestated, this makes the list fixed-sized.

PS:正如aioobe所说,这使得列表大小固定。

回答by Mathias Schwarz

You can use the Arraysclass in the standard Java API: http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)

您可以Arrays在标准 Java API 中使用该类:http: //download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)

List<String> strings = Arrays.asList("s1", "s2", "s3");

Be aware that the resultning list is fixed-size (you cannot add to it).

请注意,结果列表是固定大小的(您无法添加)。

回答by aioobe

Java 9+

爪哇 9+

Java 9 introduces a convenience method List.ofused as follows:

Java 9 引入了一种方便的方法,List.of使用如下:

List<String> l = List.of("s1", "s2", "s3");

Java 8 and older

Java 8 及更早版本

Here are a few alternatives:

这里有一些替代方案:

// Short, but the resulting list is fixed size.
List<String> list1 = Arrays.asList("s1", "s2", "s3");

// Similar to above, but the resulting list can grow.
List<String> list2 = new ArrayList<>(Arrays.asList("s1", "s2", "s3"));

// Using initialization block. Useful if you need to "compute" the strings.
List<String> list3 = new ArrayList<String>() {{
    add("s1");
    add("s2");
    add("s3");
}};



When it comes to arrays, you could initialize it at the point of declaration like this:

当涉及到数组时,您可以在声明点初始化它,如下所示:

String[] arr = { "s1", "s2", "s3" };

If you need to reinitialize it or create it without storing it in a variable, you do

如果您需要重新初始化或创建它而不将其存储在变量中,您可以

new String[] { "s1", "s2", "s3" }

If the string constants are may though, it would look like

如果字符串常量是可能的,它看起来像

String[] arr = { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10",
                 "s11", "s12", "s13" };

In these I usually prefer writing

在这些我通常更喜欢写作

String[] arr = "s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13".split(",");

回答by MikaelF

I am not familiar with Guava, but almost all solutions mentioned in other answers and using the JDK suffer have some flaws:

我对 Guava 不熟悉,但几乎所有其他答案中提到的解决方案和使用 JDK 都存在一些缺陷:

  1. The Arrays.asListmethod returns a fixed-size list.

  2. {{Double-brace initialization}} is known to create classpath clutter and slow down execution. It also requires one line of code per element.

  3. Java 9: the static factory method List.ofreturns a structurally immutable list. Moreover, List.ofis value-based, and therefore its contract does not guarantee that it will return a new object each time.

  1. Arrays.asList方法返回一个固定大小的列表。

  2. {{双括号初始化}} 会造成类路径混乱并减慢执行速度。它还需要每个元素一行代码。

  3. Java 9:静态工厂方法List.of返回结构上不可变的列表。而且,List.of基于值的,因此它的合约不保证每次都会返回一个新对象。



Here is a Java 8 one-liner for gathering multiple individual objects into an ArrayList, or any collection for that matter.

这是一个 Java 8 one-liner,用于将多个单独的对象收集到一个ArrayList或任何与此相关的集合中。

List<String> list = Stream.of("s1", "s2", "s3").collect(Collectors.toCollection(ArrayList::new));

Note: aioobe's solution of copying a transitory collection (new ArrayList<>(Arrays.asList("s1", "s2", "s3"))) is also excellent.

注意:aioobe 的复制临时集合 ( new ArrayList<>(Arrays.asList("s1", "s2", "s3")))的解决方案也很出色。

回答by Donald Raab

With Eclipse Collections, you can write the following:

使用Eclipse Collections,您可以编写以下内容:

List<String> list = Lists.mutable.with("s1", "s2", "s3");

You can also be more specific about the types and whether they are Mutable or Immutable.

您还可以更具体地了解类型以及它们是可变的还是不可变的。

MutableList<String> mList = Lists.mutable.with("s1", "s2", "s3");
ImmutableList<String> iList = Lists.immutable.with("s1", "s2", "s3");

You can also do the same with Sets, Bags and Maps:

你也可以对 Sets、Bags 和 Maps 做同样的事情:

Set<String> set = Sets.mutable.with("s1", "s2", "s3");
MutableSet<String> mSet = Sets.mutable.with("s1", "s2", "s3");
ImmutableSet<String> iSet = Sets.immutable.with("s1", "s2", "s3");

Bag<String> bag = Bags.mutable.with("s1", "s2", "s3");
MutableBag<String> mBag = Bags.mutable.with("s1", "s2", "s3");
ImmutableBag<String> iBag = Bags.immutable.with("s1", "s2", "s3");

Map<String, String> map = 
    Maps.mutable.with("s1", "s1", "s2", "s2", "s3", "s3");
MutableMap<String, String> mMap = 
    Maps.mutable.with("s1", "s1", "s2", "s2", "s3", "s3");
ImmutableMap<String, String> iMap = 
    Maps.immutable.with("s1", "s1", "s2", "s2", "s3", "s3");

There are factories for SortedSets, SortedBags and SortedMaps as well.

还有 SortedSets、SortedBags 和 SortedMaps 的工厂。

SortedSet<String> sortedSet = SortedSets.mutable.with("s1", "s2", "s3");
MutableSortedSet<String> mSortedSet = SortedSets.mutable.with("s1", "s2", "s3");
ImmutableSortedSet<String> iSortedSet = SortedSets.immutable.with("s1", "s2", "s3");

SortedBag<String> sortedBag = SortedBags.mutable.with("s1", "s2", "s3");
MutableSortedBag<String> mSortedBag = SortedBags.mutable.with("s1", "s2", "s3");
ImmutableSortedBag<String> iSortedBag = SortedBags.immutable.with("s1", "s2", "s3");

SortedMap<String, String> sortedMap =
        SortedMaps.mutable.with("s1", "s1", "s2", "s2", "s3","s3");
MutableSortedMap<String, String> mSortedMap =
        SortedMaps.mutable.with("s1", "s1", "s2", "s2", "s3","s3");
ImmutableSortedMap<String, String> iSortedMap =
        SortedMaps.immutable.with("s1", "s1", "s2", "s2", "s3","s3");

Note:I am a committer for Eclipse Collections.

注意:我是 Eclipse Collections 的提交者。

回答by LazerBanana

JDK2

JDK2

List<String> list = Arrays.asList("one", "two", "three");

JDK7

JDK7

//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");

JDK8

JDK8

List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());

JDK9

JDK9

List<String> list = List.of("one", "two", "three");

Plus there are lots of other ways supplied by other libraries like Guava.

此外,其他库(如 Guava)还提供了许多其他方式。