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.
I am not familiar with Guava, but almost all solutions mentioned in other answers and using the JDK suffer have some flaws:
The Arrays.asList
method returns a fixed-size list.
{{Double-brace initialization}} is known to create classpath clutter and slow down execution. It also requires one line of code per element.
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.