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


Java EnumMap keySet()用法及代碼示例


Java中的Java.util.EnumMap.keySet()方法用於返回映射中包含的鍵的設置視圖。

用法:

Enum_Map.keySet()

參數:該方法不接受任何參數。


返回值:該方法返回映射中包含的鍵的設置視圖。

以下示例程序旨在說明keySet()函數:

示例1:

// Java program to demonstrate keySet() 
import java.util.*; 
  
// An enum of geeksforgeeks 
public enum gfg { 
    India, 
    United_States, 
    China 
}; 
  
class Enum_demo { 
    public static void main(String[] args) 
    { 
  
        EnumMap<gfg, String> mp = new 
                    EnumMap<gfg, String>(gfg.class); 
  
        // Values are associated 
        mp.put(gfg.India, "61.7%"); 
        mp.put(gfg.United_States, "18.2%"); 
        mp.put(gfg.China, "2.5%"); 
  
        // Prints the map 
        System.out.println("Mappings: " + mp); 
  
        // Store the set view of the key 
        Set<gfg> set_view = mp.keySet(); 
  
        // Print the result 
        System.out.println("Set view of the key: " +  
                                            set_view); 
    } 
}
輸出:
Mappings: {India=61.7%, United_States=18.2%, China=2.5%}
Set view of the key: [India, United_States, China]

示例2:

// Java program to demonstrate keySet() 
import java.util.*; 
  
// An enum of geeksforgeeks 
public enum gfg { 
    Global_today, 
    India_today 
}; 
  
class Enum_demo { 
    public static void main(String[] args) 
    { 
  
        EnumMap<gfg, Integer> mp =  
                new EnumMap<gfg, Integer>(gfg.class); 
  
        // Values are associated 
        mp.put(gfg.Global_today, 799); 
        mp.put(gfg.India_today, 69); 
  
        // Prints the map 
        System.out.println("Mappings: " + mp); 
  
        // Store the set view of the key 
        Set<gfg> set_view = mp.keySet(); 
  
        // Print the result 
        System.out.println("Set view of the key: " + 
                                             set_view); 
    } 
}
輸出:
Mappings: {Global_today=799, India_today=69}
Set view of the key: [Global_today, India_today]


相關用法


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