本文主要介绍Java中初始化ArrayList或List方法代码,及使用一行代码进行集合初始化的方法。

1、使用实例初始化程序创建匿名内部类方式

//一般方式初始化
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
//创建匿名内部类方式初始化
ArrayList<String> list = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
}};
//下面代码是初始化一个不可变的List,而不是一个ArrayList
List<String> list = ["A", "B", "C"];

2、使用Arrays.asList初始化

List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
 //只有一个元素
List<String> places = Collections.singletonList("Buenos Aires");
//用ArrayList创建可变列表,可以用ArrayList通过不可变列表来创建
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

3、使用List.of方法初始化

//需要在Java 10,11,12或更高版本中使用
var strings = List.of("foo", "bar", "baz");
//需要在Java 9或更高版本中使用
List<String> strings = List.of("foo", "bar", "baz");
//Java 8或更早版本
List<String> strings = Arrays.asList("foo", "bar", "baz");
//import static java.util.Arrays.asList;  //静态导入

注意:上面创建的是一个不可变的List

4、使用Stream.of方法初始化

//静态导入
import static java.util.stream.Collectors.toList;
List<String> strings = Stream.of("foo", "bar", "baz").collect(toList());

//静态导入
import static java.util.stream.Collectors.toCollection;

ArrayList<String> strings = Stream.of("foo", "bar")
                             .collect(toCollection(ArrayList::new));
strings.add("baz");

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

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

5、使用Google_Guava初始化

文档https://github.com/google/guava/wiki/CollectionUtilitiesExplained

ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");



推荐文档