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

后端 未结 7 877
无人共我
无人共我 2020-12-04 17:39

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.

相关标签:
7条回答
  • 2020-12-04 18:17

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

    1. The Arrays.asList method 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.of is value-based, and therefore its contract does not guarantee that it will return a new object each time.


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

    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.

    0 讨论(0)
提交回复
热议问题