The singletonList() method of java.util.Collections class is used to return an immutable list containing only the specified object. The returned list is serializable. This list will always contain only one element thus the name singleton list. When we try to add/remove an element on the returned singleton list, it would give UnsupportedOperationException.
Syntax:
public static List singletonList(T o)
Parameters:
This method takes the object o as a parameter to be stored in the returned list.
Return Value:
This method returns an immutable list containing only the specified object.
Below are the examples to illustrate the singletonList() method
Example 1:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
List<String> list = Collections.singletonList( "E" );
System.out.println( "singletonList : " + list);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output
singletonList : [E]
Example 2:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
List<Integer> list = Collections.singletonList( 20 );
System.out.println( "singletonList : " + list);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output
singletonList : [20]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!