How to Initialize a List in Java

Updated onbyAlan Morel
How to Initialize a List in Java

Lists are really useful in Java because they allow you to store a collection of items in a single variable.

When you're working with Java, it is very likely that eventually you'll need to create one yourself.

In this post, we'll learn how to initialize a list in Java.

How to initialize a list from an array in Java

The easiest way to initialize a list in Java is to initialize one using an existing array.

Let's define an array of strings:

JAVA
String[] names = {"John", "Mary", "Peter"};

Now, we can initialize a list from this array using the Arrays.asList() method.

This method takes an array as an argument and returns a list containing the same elements as the array:

JAVA
String[] names = {"John", "Mary", "Peter"}; List<String> namesList = Arrays.asList(names);

How to initialize a list from individual elements in Java

Another way to initialize a list in Java is to initialize it from individual elements.

This means, you don't need to create an array first, you can just pass the elements directly to the Arrays.asList() method.

Let's see how this works:

JAVA
List<String> namesList = Arrays.asList("John", "Mary", "Peter");

This is useful when you don't have an array of elements, but you want to initialize a list from individual elements.

How to initialize a list and then add elements to it in Java

Another way to create a list in Java is to initialize an empty list and then add elements to it using the add() method.

Let's see how this works:

JAVA
List<String> namesList = new ArrayList<>(); namesList.add("John"); namesList.add("Mary"); namesList.add("Peter");

Finally, another way to do it is by initializing it in the constructor using double-brace initialization:

JAVA
List<String> namesList = new ArrayList<String>() {{ add("John"); add("Mary"); add("Peter"); }};

For the most part, unless you need to use double-brace initialization, you should instead separately initialize the list and then add elements to it because it is more clear and readable.

Conclusion

In this post, we learned how to initialize a list in Java.

Your options include initializing a list from an array, initializing a list from individual elements, and initializing a list and then adding elements to it.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.