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


要從 HashMap 檢索鍵集,請使用 keyset() 方法。但是,對於值集,請使用 values() 方法

建立一個 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();
Iterator i = keys.iterator();
while (i.hasNext()) {
   System.out.println(i.next());
}

檢索值 −

Collection getValues = hm.values();
i = getValues.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);
      System.out.println("
Keys..."); Set keys = hm.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { System.out.println(i.next()); } System.out.println("
Values..."); Collection getValues = hm.values(); i = getValues.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }

輸出

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

Keys...
Backpack
Belt
Wallet

Values...
1200
600
700

更新時間:18-6-2024

15K+ 瀏覽量

提升你的 事業

完成課程獲得認證

開始
廣告