Collections.singleton() method in Java with example
Last Updated :
02 Jul, 2021
java.util.Collections.singleton() method is a java.util.Collections class method. It creates a immutable set over a single specified element. An application of this method is to remove an element from Collections like List and Set.
Syntax:
public static Set singleton(T obj)
and
public static List singletonList(T obj)
Parameters: obj : the sole object to be stored in
the returned list or set.
Return: an immutable list/set containing only the
specified object.
Example:
myList : {"Geeks", "code", "Practice", " Error", "Java",
"Class", "Error", "Practice", "Java" }
To remove all "Error" elements from our list at once, we use
singleton() method
myList.removeAll(Collections.singleton("Error"));
After using singleton() and removeAll, we get following.
{"Geeks", "code", "Practice", "Java", "Class", "Practice", "Java" }
Java
import java.util.*;
class GFG {
public static void main(String args[])
{
String[] geekslist = { "1" , "2" , "4" , "2" , "1" , "2" ,
"3" , "1" , "3" , "4" , "3" , "3" };
List geekslist1 = new ArrayList(Arrays.asList(geekslist));
System.out.println( "Original geeklist1: " + geekslist1);
geekslist1.remove( "1" );
System.out.println( "geekslist1 after removal of 1 without"
+ " singleton " + geekslist1);
geekslist1.remove( "1" );
System.out.println( "geekslist1 after removal of 1 without"
+ " singleton " + geekslist1);
geekslist1.remove( "2" );
System.out.println( "geekslist1 after removal of 2 without"
+ " singleton " + geekslist1);
List geekslist2 = new ArrayList(Arrays.asList(geekslist));
System.out.println( "\nOriginal geeklist2: " + geekslist2);
geekslist2.removeAll(Collections.singleton( "1" ));
System.out.println( "geekslist2 after removal of 1 with "
+ "singleton:" + geekslist2);
geekslist2.removeAll(Collections.singleton( "4" ));
System.out.println( "geekslist2 after removal of 4 with "
+ "singleton:" + geekslist2);
geekslist2.removeAll(Collections.singleton( "3" ));
System.out.println( "geekslist2 after removal of 3 with"
+ " singleton: " + geekslist2);
}
}
|
Output:
Original geeklist1 [1, 2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3]
geekslist1 after removal of 1 without singleton [2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3]
geekslist1 after removal of 1 without singleton [2, 4, 2, 2, 3, 1, 3, 4, 3, 3]
geekslist1 after removal of 2 without singleton [4, 2, 2, 3, 1, 3, 4, 3, 3]
Original geeklist2 [1, 2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3]
geekslist2 after removal of 1 with singleton [2, 4, 2, 2, 3, 3, 4, 3, 3]
geekslist2 after removal of 4 with singleton [2, 2, 2, 3, 3, 3, 3]
geekslist2 after removal of 3 with singleton [2, 2, 2]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...