Table of Contents
In this post, we will see how to initialize List of String in java.
Can you initialize List of String as below:
1 2 3 |
List<String> list = new List<String>(); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// ArrayList List<String> list1 = new ArrayList<String>(); // LinkedList List<String> list2 = new LinkedList<String>(); // Vector List<String> list3 = new Vector<String>(); // CopyOnWriteArrayList List<String> list4 = new CopyOnWriteArrayList<String>(); |
In most of the cases, you will initialize List with ArrayList as below.
1 2 3 4 |
// ArrayList List<String> list1 = new ArrayList<String>(); |
If you are using java 7 or greater
than you can use diamond operator with generics.
1 2 3 4 |
// ArrayList List<String> list1 = new ArrayList<>(); |
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.
1 2 3 |
List<String> list1 = Arrays.asList("India","China","Bhutan"); |
Stream.of (Java 8)
You can use java 8‘s Stream to initialize list of String with values.
1 2 3 |
List<String> list1 = Stream.of("India","China","Bhutan").collect(Collectors.toList()); |
List.of (Java 9)
Finally, java has introduced a of()
method in List class to initialize list with values in java 9.
1 2 3 |
List<String> list1 = List.of("India","China","Bhutan"); |
Using ArrayList’s add method
You can obviously initialize ArrayList with new operator and then use add method to add element to the list.
1 2 3 4 5 6 7 |
// ArrayList List<String> list1 = new ArrayList<>(); list1.add("India"); list1.add("China"); list1.add("Bhutan"); |
Using guava library
You can use guava library as well.
1 2 3 |
List<String> list1 = Lists.newArrayList("India","China","Bhutan"); |
Here is the complete example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package org.arpit.java2blog; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class ListOfStringsMain { public static void main(String[] args) { List<String> list1 = new ArrayList<>(); list1.add("India"); list1.add("China"); list1.add("Bhutan"); System.out.println(list1); // Using Arrays.asList List<String> list2= Arrays.asList("India","China","Bhutan"); System.out.println(list2); // Using Stream.of List<String> list3 = Stream.of("India","China","Bhutan").collect(Collectors.toList()); System.out.println(list3); List<String> list4 = List.of("India","China","Bhutan"); System.out.println(list4); } } |
Output:
That’s all about how to initialize List of String in java.