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.
Java 9 introduces a convenience method List.of used as follows:
List l = List.of("s1", "s2", "s3");
Here are a few alternatives:
// Short, but the resulting list is fixed size.
List list1 = Arrays.asList("s1", "s2", "s3");
// Similar to above, but the resulting list can grow.
List list2 = new ArrayList<>(Arrays.asList("s1", "s2", "s3"));
// Using initialization block. Useful if you need to "compute" the strings.
List list3 = new ArrayList() {{
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 cases I usually prefer writing
String[] arr = "s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13".split(",");