當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Collections newSetFromMap()用法及代碼示例


java.util.Collections類的newSetFromMap()方法用於返回由指定映射支持的集合。結果集顯示的排序,並發性和性能特征與支持映射相同。本質上,此工廠方法提供與任何Map實現相對應的Set實現。不需要在已經具有相應Set實現的Map實現(例如HashMap或TreeMap)上使用此方法。

用法:

public static  Set newSetFromMap(Map map)

參數:此方法將支持映射作為參數


返回值:此方法返回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


相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Collections newSetFromMap() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。