Java Collections中的newSetFromMap()方法及其示例
java.util.Collections类的 newSetFromMap() 方法用于返回由指定映射支持的集合。所得到的集合显示了与支持映射相同的排序、并发性和性能特征。本质上,该工厂方法提供了与任何映射实现相对应的集合实现。如果映射实现已经具有相应的集合实现(如HashMap或TreeMap),则不需要使用此方法。
语法:
public static Set newSetFromMap(Map map)
参数: 此方法将支持映射作为参数。
返回值: 此方法返回由映射支持的集合。
异常: 如果映射不为空,则此方法会抛出 IllegalArgumentException 。
以下是说明newSetFromMap()方法的示例。
示例1:
// Java program to demonstrate
// newSetFromMap() method
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of Map<String, Boolean>
Map<String, Boolean>
map = new WeakHashMap<String, Boolean>();
// creating object of LinkedList
Set<String> set = Collections.newSetFromMap(map);
// add values in set
set.add("A");
set.add("B");
set.add("C");
set.add("D");
// set and map values are
System.out.println("Map is: " + map);
System.out.println("Set from Map is: " + set);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Map is: {C=true, B=true, A=true, D=true}
Set from Map is: [C, B, A, D]
示例2: 用于IllegalArgumentException
// Java program to demonstrate
// newSetFromMap() method
// for IllegalArgumentException
import java.util.*;
<div class = 'outputDiv'>
<b>Output:</b>
<pre>
Set is: [C, B, A, D]
Map is: {C=true, B=true, A=true, D=true}
</pre>
</div>
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of Map<String, Boolean>
Map<String, Boolean>
map = new WeakHashMap<String, Boolean>();
// putting value in map
map.put("1", true);
// creating object of LinkedList
Set<String> set = Collections.newSetFromMap(map);
// add values in set
set.add("A");
set.add("B");
set.add("C");
set.add("D");
// set and map values are
System.out.println("Map is: " + map);
System.out.println("Set from Map is: " + set);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Exception thrown : java.lang.IllegalArgumentException: Map is non-empty