Table of Contents
In this post, we will see how to create List with One Element in java..
Using Collections.singletonList()
This is best way to create List with single element if you need an immutable List.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; import java.util.Collections; import java.util.List; public class CreateListWithSingleElementJavaCollections { public static void main(String[] args) { List<String> list = Collections.singletonList("India"); System.out.println("List: "+list); } } |
Output
1 2 3 |
List: [India] |
If you try to add element to the list, you will get exception
1 2 3 4 |
List<String> list = Collections.singletonList("India"); list.add("China"); |
1 2 3 4 5 6 |
Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.AbstractList.add(AbstractList.java:153) at java.base/java.util.AbstractList.add(AbstractList.java:111) at org.arpit.java2blog.CreateListWithSingleElementJavaCollections.main(CreateListWithSingleElementJavaCollections.java:10) |
Using Array.asList() method [ Immuatable list]
Arrays.asList()
method can be used to create list with single element. Created list will be immutable list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; import java.util.Arrays; import java.util.List; public class CreateListWithSingleElementJava { public static void main(String[] args) { List<String> list = Arrays.asList( "India"); System.out.println(list); } } |
If you try to add element to the list, you will get exception
1 2 3 4 |
List<String> list = Arrays.asList( "India"); list.add("China"); |
1 2 3 4 5 6 |
Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.AbstractList.add(AbstractList.java:153) at java.base/java.util.AbstractList.add(AbstractList.java:111) at org.arpit.java2blog.CreateListWithSingleElementJava.main(CreateListWithSingleElementJava.java:10) |
Using new ArrayList with Array.asList() method [ Mutable list]
If you need mutable list, you can use Arrays.asList()
and pass the result into new ArrayList.
1 2 3 |
List<String> list = new ArrayList<String>(Arrays.asList(s)); |
As this is mutable list, you can add elements to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package org.arpit.java2blog; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CreateListWithSingleElementNewArrayList { public static void main(String[] args) { List<String> list = new ArrayList(Arrays.asList( "India")); System.out.println("List: "+list); list.add("China"); System.out.println("List after adding an element: "+list); } } |
Output
1 2 3 4 |
List: [India] List after adding an element: [India, China] |
You can also new ArrayList with Collections.singletonList()
to create mutable list.
1 2 3 |
List<String> list = new ArrayList<String>(Collections.singletonList(s)); |
Further reading:
That’s all about how to create ArrayList with one element in java.