Initialization of an ArrayList in one line

后端 未结 30 2252
北恋
北恋 2020-11-22 01:10

I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList places = new ArrayList();
places.add(\         


        
30条回答
  •  梦毁少年i
    2020-11-22 01:55

    Collection literals didn't make it into Java 8, but it is possible to use the Stream API to initialize a list in one rather long line:

    List places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());
    

    If you need to ensure that your List is an ArrayList:

    ArrayList places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));
    

提交回复
热议问题