Java Utility Library

Java Collections - singletonList() Method



The java.util.Collections.singletonList() method returns an immutable list containing only the specified object. The returned list is serializable.

Syntax

public static <T> List<T> singletonList(T o)

Here, T is the type of element in the list.


Parameters

o Specify the sole object to be stored in the returned list.

Return Value

Returns an immutable list containing only the specified object.

Exception

NA.

Example:

In the example below, the java.util.Collections.singletonList() method returns an immutable list containing only the specified elements.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    String[] lst = {"10", "20", "30", "40", "10", "10", "20"};

    //creating list
    List<String> MyList = 
        new ArrayList<String>(Arrays.asList(lst)); 

    //printing the list
    System.out.println("MyList contains: " + MyList);

    //creating singleton list
    MyList = Collections.singletonList("25");

    //printing the list
    System.out.println("MyList contains: " + MyList);
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40, 10, 10, 20]
MyList contains: [25]

❮ Java.util - Collections