Initialize List of String in java

In this post, we will see how to initialize List of String in java.

Can you initialize List of String as below:

You can't because List is an interface and it can not be instantiated with new List().

You need to instantiate it with the class that implements the List interface.

Here are the common java Collections classes which implement List interface.

In most of the cases, you will initialize List with ArrayList as below.

If you are using java 7 or greater than you can use diamond operator with generics.

Initialize List of Strings with values

There are many ways to initialize list of Strings with values.

Arrays’s asList

You can use Arrays’s asList method to initialize list with values.

Stream.of (Java 8)

You can use java 8‘s Stream to initialize list of String with values.

List.of (Java 9)

Finally, java has introduced a of() method in List class to initialize list with values in java 9.

Using ArrayList’s add method

You can obviously initialize ArrayList with new operator and then use add method to add element to the list.

Using guava library

You can use guava library as well.

Here is the complete example.

Output:

[India, China, Bhutan] [India, China, Bhutan] [India, China, Bhutan] [India, China, Bhutan]

That’s all about how to initialize List of String in java.

Was this post helpful?

Leave a Reply

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