Java 程式以檢索 HashMap 中的所有鍵的集合


首先,建立一個 HashMap 並新增元素

HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));

現在,檢索所有鍵

Set keys = hm.keySet();
System.out.println("
Keys..."); Iterator i = keys.iterator(); while (i.hasNext()) {    System.out.println(i.next()); }

以下是獲取 HashMap 中所有鍵集合的示例

示例

 線上演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      hm.put("Backpack", new Integer(1200));
      System.out.println("Map = "+hm);
      Set keys = hm.keySet();
      System.out.println("
Keys..."); Iterator i = keys.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }

以下是輸出

Map = {Backpack=1200, Belt=600, Wallet=700}
Keys...
Backpack
Belt
Wallet

更新於:30-Jul-2019

256 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告