- Initialize List of String in java
- Initialize List of Strings with values
- Arrays’s asList
- Stream.of (Java 8)
- List.of (Java 9)
- Using ArrayList’s add method
- Using guava library
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Convert UUID to String in Java
- Repeat String N times in Java
- How to Replace Space with Underscore in Java
- How to Replace Comma with Space in Java
- Remove Parentheses From String in Java
- Escape percent sign in String’s format method in java
- Initialize List with Values in Java
- Java 8 or earlier
- Java 9 or later
- Using Streams
- See Also
- Initialize List of String in Java
- Use ArrayList , LinkedList and Vector to Instantiate a List of String in Java
- Use Arrays.asList to Instantiate a List of String in Java
- Use Stream in Java 8 to Instantiate a List of String in Java
- Use List.of to Instantiate a List of String in Java
- Related Article — Java List
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.
That’s all about how to initialize List of String in java.
Was this post helpful?
Share this
Related Posts
Author
Related Posts
Convert UUID to String in Java
Table of ContentsIntroductionUUID class in JavaConvert UUID to String in Java Introduction In this article, we will have a look on How to Convert UUID to String in Java. We will also shed some light on the concept of UUID, its use, and its corresponding representation in Java class. Let us have a quick look […]
Repeat String N times in Java
Table of ContentsIntroductionWhat is a String in Java?Repeat String N times in JavaSimple For Loop to Repeat String N Times in JavaUsing Recursion to Repeat String N Times in JavaString.format() method to Repeat String N Times in JavaUsing String.repeat() method in Java 11 to Repeat String N TimesRegular Expression – Regex to Repeat String N […]
How to Replace Space with Underscore in Java
Table of ContentsReplace space with underscore in java1. Using replace() method2. Using replaceAll() method Learn about how to replace space with underscore in java. Replace space with underscore in java 1. Using replace() method Use String’s replace() method to replace space with underscore in java. String’s replace() method returns a string replacing all the CharSequence […]
How to Replace Comma with Space in Java
Table of ContentsReplace comma with space in java1. Using replace() method2. Using replaceAll() method Learn about how to replace comma with space in java. Replace comma with space in java 1. Using replace() method Use String’s replace() method to replace comma with space in java. Here is syntax of replace() method: [crayon-64be4f2841204344966778/] [crayon-64be4f2841209175847002/] Output: 1 […]
Remove Parentheses From String in Java
Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusion Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text data at contiguous […]
Escape percent sign in String’s format method in java
Table of ContentsEscape Percent Sign in String’s Format Method in JavaEscape Percent Sign in printf() Method in Java In this post, we will see how to escape Percent sign in String’s format() method in java. Escape Percent Sign in String’s Format Method in Java String’s format() method uses percent sign(%) as prefix of format specifier. […]
Initialize List with Values in Java
In this tutorial, we’ll learn different ways to initialize List, ArrayList and LinkedList with values in single line in Java.
Java 8 or earlier
Initialize Immutable List
This is the simplest way to initialize a List:-
/** * Immutable list with inline elements */ ListString> list = Arrays.asList("foo", "bar", "baz"); /** * Immutable list with array */ String[] names = "foo", "bar" >; ListString> anotherList = Arrays.asList(names); anotherList.add("baz") // Throw UnsupportedOperationException exception
The only drawback is that the initalized list is immutable. That means adding or removing elements in the list throw java.lang.UnsupportedOperationException exception.
It is useful when you just need it for iteration and read-only purpose.
Initialize Mutable List
If you want to intialize a mutable list where you can add or remove elements. You wrap immutable list with ArrayList or LinkedList :-
ListString> arrayList = new ArrayList<>(Arrays.asList("foo", "bar")); arrayList.add("baz"); // It works! ListString> linkedList = new LinkedList<>(Arrays.asList("foo", "bar")); linkedList.remove("foo"); // It works!
Collections.addAll()
You can also use Collections.addAll() static method to add values to ArrayList or LinkedList
ListString> arrayList = new ArrayListString>(); Collections.addAll(arrayList, "foo", "bar", "baz");
Double Brace Initialization
Another way is to making an anonymous inner class with an instance initializer. This is also known as an double brace initialization. However that looks like an overkill to create a inner class just to create an ArrayList or LinkedList
ListString> strings = new ArrayListString>() add("A"); add("B"); add("C"); > >;
Java 9 or later
Initialize Immutable List
List.of() is added in Java 9 which can be used to initialize an immutable list with values.
ListString> list = List.of("foo", "bar"); list.add("baz") // Throw UnsupportedOperationException exception
With Java 10 or later, this can be even more shortened with the var keyword.
var list = List.of("foo", "bar", "baz");
Initialize Mutable List
You can also define mutable list with ArrayList or LinkedList wrapper:-
ListString> arrayList = new ArrayList<>(List.of("foo", "bar")); arrayList.add("baz"); // It works! ListString> linkedList = new LinkedList<>(List.of("foo", "bar")); linkedList.remove("foo"); // It works!
Using Streams
You can also use Stream API which is more flexible:-
StreamString> strings = Stream.of("foo", "bar", "baz");
You can combine two or more Streams like this:-
StreamString> strings = Stream.concat(Stream.of("foo", "bar"), Stream.of("baz", "qux"));
You can transform a Stream into mutable List or ArrayList like this:-
ListString> list = Stream.of("foo", "bar", "baz").collect(Collectors.toList()); list.remove("baz"); // It works! ListString> arrayList = Stream.of("foo", "bar").collect(Collectors.toCollection(ArrayList::new)); arrayList.add("baz"); // It works!
See Also
Ashish Lahoti is a Software Engineer with 12+ years of experience in designing and developing distributed and scalable enterprise applications using modern practices. He is a technology enthusiast and has a passion for coding & blogging.
Initialize List of String in Java
- Use ArrayList , LinkedList and Vector to Instantiate a List of String in Java
- Use Arrays.asList to Instantiate a List of String in Java
- Use Stream in Java 8 to Instantiate a List of String in Java
- Use List.of to Instantiate a List of String in Java
In this tutorial, we will see various ways in which we can Initialize a list of string in Java. Since the list is an interface, we can not directly instantiate it.
Use ArrayList , LinkedList and Vector to Instantiate a List of String in Java
A List is a child interface of Collections in Java. It is an ordered collection of objects which can store duplicate values. The instance of List can be created using classes that implement the List Interface.
ArrayList , Vector , LinkedList and Stack are a few of these classes. We create an instance myList of a List using new ArraList() . Hence, we can declare and create an instance of List using any of the following ways shown below and perform various operations on that List .
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Vector; public class ListExample public static void main (String [] args ) ListString> myList = new ArrayListString>(); ListFruits> lList = new LinkedListFruits>(); ListInteger> vList = new VectorInteger>(); myList.add("Happy"); myList.add("Coding"); lList.add(new Fruits("Grapes", "Green")); lList.add(new Fruits("Apple","Red")); vList.add(1); vList.add(4); vList.add(9); vList.add(7); vList.remove(2); for (String s :myList) System.out.println(s); > for(Fruits f : lList ) System.out.println(f.name + " is " +f.color + " in color."); > for (int i : vList) System.out.println(i); > > > class Fruits String name; String color; Fruits(String name , String color) this.name = name; this.color = color; > >
Happy Coding Grapes is Green in color. Apple is Red in color. 1 4 7
Use Arrays.asList to Instantiate a List of String in Java
The Arrays.asList method returns a fixed-size list that is backed by an array. This is just a wrapper that makes the array available as a list. We can not modify this list as it is immutable.
Here in the code, we get an instance of List named myList whose length can not be modified.
import java.util.Arrays; import java.util.List; public class ListExmp public static void main(String[] args) ListString> myList = Arrays.asList("John","Ben","Gregor","Peter"); String name = myList.get(3); System.out.println(name); > >
Use Stream in Java 8 to Instantiate a List of String in Java
Java 8 Stream includes wrappers around a data source that makes a bulky process on the data easy and convenient.
The Stream.of() method constructs a stream of data and collects them in a list. The Collector interface provides the logic for this operation. The Collector.toList() collects all the stream elements into an instance of List .
import java.util.List; import java.util.stream.Stream; import java.util.stream.Collectors; public class ListExmp public static void main(String[] args) ListString> list = Stream.of("john", "doe").collect(Collectors.toList()); if(list.contains("doe")) System.out.println("doe is there"); >else System.out.println("doe is not there"); > > >
Use List.of to Instantiate a List of String in Java
The List.of is the new method introduced in Java 9. In the code below, the List.of() method takes any number of arguments and returns an immutable list. We have immutableList as an unmodifiable instance of List .
We have to instantiate ArrayList with an immutable list as a parameter to create a mutable list. As shown in the code below, modifications can be made to the mutableList instance of the List .
import java.util.List; import java.util.ArrayList; public class ListExmp public static void main(String[] args) ListString> immutableList = List.of("One","Two","Three","Four","Five"); ListString> mutableList = new ArrayList<>(List.of("Six", "Seven", "Eight")); for(String l:immutableList) System.out.println(l); > System.out.println("XXXXXX"); mutableList.add("Nine"); for(String l:mutableList) System.out.println(l); > > >
One Two Three Four Five XXXXXX Six Seven Eight Nine
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Related Article — Java List
Copyright © 2023. All right reserved