How to populate a static List (ArrayList, LinkedList) in Java (syntax)

Java FAQ: How do I initialize/populate a static List (ArrayList, LinkedList) in Java?

Java 9

If you can use Java 9 and newer, you can use this syntax:

List<String> strings = new ArrayList<>(List.of("Hello", "world"));

Prior to Java 9

For versions of Java prior to Java 9 I show an older approach below, but I just learned about this relatively-simple way to create and populate a Java ArrayList in one step:

List<String> strings = new ArrayList<>(
    Arrays.asList("Hello", "world")
);

or in this format, if you prefer:

List<String> strings = new ArrayList<>(Arrays.asList(
    "Hello",
    "world"
));

I show my older approach below, but if you’re using Java 7 or Java 8, this seems like a good approach.

My older approach

This is the older, pre-Java 9 approach I used to use to create a static List in Java (ArrayList, LinkedList):

static final List<Integer> nums = new ArrayList<Integer>() {{
    add(1);
    add(2);
    add(3);
}};

As you can guess, that code creates and populates a static List of integers. If your List needs to contain a different data type, just change the Integer to whatever your desired type is, and of course change the add method calls accordingly.

Complete static initialization List example

As a little summary, and for the sake of completeness, the following Java source code shows a complete working example that includes the previous static initialization example:

import java.util.ArrayList;
import java.util.List;

public class SumTest1 {

    // CREATE AND POPULATE A STATIC JAVA LIST
    static final List<Integer> nums = new ArrayList<Integer>() {{
        add(1);
        add(2);
        add(3);
    }};
    
    public static void main(String[] args) {
        int total = sum(nums);
        System.out.println("Sum: " + total);
    }

    public static int sum(List<Integer> ints) {
        int sum = 0;
        for (int i : ints) {
            sum += i;
        }
        return sum;
    }

}

If you wanted to see the syntax required to create and populate a List (ArrayList, LinkedList) in Java, I hope this is helpful.

... this post is sponsored by my books ...