Java Collections - singleton() Method
The java.util.Collections.singleton() method returns an immutable set containing only the specified object. The returned set is serializable.
Syntax
public static <T> Set<T> singleton(T o)
Here, T is the type of element in the set.
Parameters
o |
Specify the sole object to be stored in the returned set. |
Return Value
Returns an immutable set containing only the specified object.
Exception
NA.
Example:
In the example below, the java.util.Collections.singleton() method returns an immutable set 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 two lists List<String> MyList1 = new ArrayList<String>(Arrays.asList(lst)); List<String> MyList2 = new ArrayList<String>(Arrays.asList(lst)); //remove occurrences of "10" from MyList1 //using remove() method MyList1.remove("10"); System.out.println("MyList1 contains: " + MyList1); //remove occurrences of "10" from MyList2 //using singleton() method MyList2.removeAll(Collections.singleton("10")); System.out.println("MyList2 contains: " + MyList2); } }
The output of the above code will be:
MyList1 contains: [20, 30, 40, 10, 10, 20] MyList2 contains: [20, 30, 40, 20]
❮ Java.util - Collections