Java Collections.singleton()方法及示例
java.util.Collections.singleton() 方法是一个java.util.Collections类的方法。它在一个单一的指定元素上创建一个不可变的集合。这个方法的一个应用是将一个元素从List和Set等集合中移除。
语法
public static Set singleton(T obj)
and
public static List singletonList(T obj)
Java
参数: obj : 唯一的对象将被存储在 返回列表或集合。
返回:一个只包含指定对象的不可变的列表/集合。指定的对象。
示例:
myList : {"Geeks", "code", "Practice", " Error", "Java",
"Class", "Error", "Practice", "Java" }
Java
为了一次性从我们的列表中删除所有 “错误 “元素,我们使用
singleton()方法
myList.removeAll(Collections.singleton(“Error”))。
在使用singleton()和removeAll之后,我们得到了以下结果。
{“Geeks”, “code”, “Practice”, “Java”, “Class”, “Practice”, “Java” }
// Java program to demonstrate
// working of singleton()
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" };
// Creating a list and removing
// elements without use of singleton()
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);
/* Creating another list and removing
its elements using singleton() method */
List geekslist2 = new ArrayList(Arrays.asList(geekslist));
System.out.println("\nOriginal geeklist2: " + geekslist2);
// Selectively delete "1" from
// all it's occurrences
geekslist2.removeAll(Collections.singleton("1"));
System.out.println("geekslist2 after removal of 1 with "
+ "singleton:" + geekslist2);
// Selectively delete "4" from
// all it's occurrences
geekslist2.removeAll(Collections.singleton("4"));
System.out.println("geekslist2 after removal of 4 with "
+ "singleton:" + geekslist2);
// Selectively delete "3" from
// all it's occurrences
geekslist2.removeAll(Collections.singleton("3"));
System.out.println("geekslist2 after removal of 3 with"
+ " singleton: " + geekslist2);
}
}
Java
输出
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]
Java