java.util.Collections.singletonList() Method
Advertisements
Description
The singletonList(T) method is used to return an immutable list containing only the specified object.
Declaration
Following is the declaration for java.util.Collections.singletonList() method.
public static <T> List<T> singletonList(T o)
Parameters
o--This is the sole object to be stored in the returned list.
Return Value
The method call returns an immutable list containing only the specified object.
Exception
NA
Example
The following example shows the usage of java.util.Collections.singletonList()
package com.tutorialspoint;
import java.util.*;
public class CollectionsDemo {
public static void main(String args[]) {
// create an array of string objs
String init[] = { "One", "Two", "Three", "One", "Two", "Three" };
// create one list
List list = new ArrayList(Arrays.asList(init));
System.out.println("List value before: "+list);
// create singleton list
list = Collections.singletonList("TP");
System.out.println("List value after: "+list);
}
}
Let us compile and run the above program, this will produce the following result.
List value before: [One, Two, Three, One, Two, Three] List value after: [TP]