Home  >  Article  >  Java  >  An article explaining 8 ways to initialize a List collection in Java (with code)

An article explaining 8 ways to initialize a List collection in Java (with code)

奋力向前
奋力向前forward
2021-09-13 10:26:126916browse

In the previous article "A Brief Analysis of Server Code Deployment in Linux (Sharing)", we learned about server code deployment in Linux. The following article will give you an understanding of the 8 ways to initialize a List collection in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

An article explaining 8 ways to initialize a List collection in Java (with code)

List is a commonly used collection in development. The following are several ways to initialize List.

Normal way

List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("getList1: " + list);

Output

getList1: [1, 2, 3]

Arrays Tool Class

// 生成的list不可变
List<String> list = Arrays.asList("1", "2", "3");
System.out.println("getList2: " + list);
// 如果要可变需要用ArrayList包装一下
List<String> numbers = new ArrayList<>(Arrays.asList("1", "2", "3"));
numbers.add("4");
System.out.println("numbers: " + numbers);

Output

getList2: [1, 2, 3]
numbers: [1, 2, 3, 4]

Collections Tool Class

// 生成的list不可变
List<String> list = Collections.nCopies(3, "1");
System.out.println("getList3: " + list);
// 如果要可变需要用ArrayList包装一下
List<String> dogs = new ArrayList<>(Collections.nCopies(3, "dog"));
dogs.add("dog");
System.out.println("dogs: " + dogs);

Output

getList3: [1, 1, 1]
dogs: [dog, dog, dog, dog]

Lists Tool Class

List<String> list = Lists.newArrayList("1", "2", "3");
System.out.println("getList4: " + list);

Output

getList4: [1, 2, 3]

Anonymous inner class

List<String> list = new ArrayList<String>() {{
     add("1");
     add("2");
     add("3");
}};
System.out.println("getList5: " + list);

Output

getList5: [1, 2, 3]

ImmutableList

List<String> list = ImmutableList.of("1", "2", "3");
System.out.println("getList6: " + list);

Output

getList6: [1, 2, 3]

Java8 Stream

List<String> list = Stream.of("1", "2", "3").collect(Collectors.toList());
System.out.println("getList7: " + list);

Output

getList7: [1, 2, 3]

Java9 List.of

List<String> list = List.of{"1", "2", "3"};
System.out.println("getList8: " + list);

Output

getList8: [1, 2, 3]

Recommended learning: Java video tutorial

The above is the detailed content of An article explaining 8 ways to initialize a List collection in Java (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:chuchur.com. If there is any infringement, please contact admin@php.cn delete