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

Viewed 84711

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 Answers

JDK2

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

JDK7

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

JDK8

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

JDK9

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

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

Related