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

后端 未结 7 923
无人共我
无人共我 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 17:55

    JDK2

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

    JDK7

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

    JDK8

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

    JDK9

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

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

提交回复
热议问题