Java FAQ: How do I initialize/populate a static List
(ArrayList
, LinkedList
) in Java?
Java 9
When you’re using Java 9 and newer — Java 11, 14, 17, etc. — you can use this concise syntax to populate a static List
:
List<String> strings = new ArrayList<>(List.of("Hello", "world"));
Prior to Java 9
For Java 8 and older JVMs, I show an older approach down 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: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |