Java Tutorial: How to Populate a Static List in Java?

By | November 3, 2021
How to populate a static List

In previous articles, we have seen methods to add numbers from a static list using Java 7 and 8 versions. In this article, we will learn how to populate a static list in Java 9 and also see examples with string. The methods work for all data types in the same way. We can follow the same approach with older Java versions, which we will show with examples.

How to Populate a Static List in Java 9?

In Java 9, factory methods have been introduced to populate lists using a single line of code. These apply to all the collection objects. For example:

List<String> myList = new ArrayList<String>(List.of("Welcome", "to", "my", "list"));
System.out.println(myList);

Note that this will work without the ‘new ArrayList’ as well:

List<String> myList = List.of("Welcome", "to", "my", "list");

You can use it for linked lists also:

      List<String> myList = new LinkedList<String>(List.of("Welcome", "to", "my", "list"));

In the above method, you can add elements at any point using the List.of() method. Prior to Java9, we could use the asList() method of the Arrays class to do the same:

Vamware
List<String> myList = Arrays.asList("Welcome", "to", "my", "list");
System.out.println(myList);

However, this list resulting from Arrays.asList() will be of fixed size and results in the java.lang.UnsupportedOperationException exception if we add to it:

/* This will throw an exception */
myList.add("New");
System.out.println(myList);

To dynamically add elements in this list using Java 8, you need to use streams. Before the introduction of streams, we added elements one by one to the list:

Vamware
List<String> myOldList = new ArrayList<String>();
myOldList.add("Welcome");
myOldList.add("to");

You can use any of the above methods to create and populate a static list in Java. Nonetheless, the first two methods are more effective and shorter.

Conclusion

We have seen the various ways in which a static list can be populated in different Java versions. To populate a static list in Java, we can also use another method known as double brace initialization. The outer braces cover an anonymous inner class, which is a subclass of ArrayList.

List<String> subjects = new ArrayList<String>() {{add("English"); add("Math"); add("Science");}};

However, it is an anti-pattern and shouldn’t be your preferred method for populating a static list in Java.

People are also reading: 

Leave a Reply

Your email address will not be published. Required fields are marked *