Thursday, September 4, 2025
HomeLanguagesJavaCollections singletonList() method in Java with Examples

Collections singletonList() method in Java with Examples

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




// Java program to demonstrate
// singletonList() method
// for <String> Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // create singleton list
            // using method singletonList() method
            List<String> list = Collections.singletonList("E");
 
            // print the list
            System.out.println("singletonList : " + list);
        }
 
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output

singletonList : [E]

Example 2: 

Java




// Java program to demonstrate
// singletonList() method
// for <Integer> Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // create singleton list
            // using method singletonList() method
            List<Integer> list = Collections.singletonList(20);
 
            // print the list
            System.out.println("singletonList : " + list);
        }
 
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output

singletonList : [20]
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6748 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS