從 Java 中的 HashMap 中檢索一組 Map.Entry 元素


建立一個 HashMap 並向其中新增元素 -

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

以下是用於檢索一組 Map.Entry 元素的程式碼段 -

Set s = hm.entrySet();
Iterator iter = s.iterator();
System.out.println("
Key\tValue"); while (iter.hasNext()) { Map.Entry e = (Map.Entry) iter.next(); System.out.println(e.getKey() + " " + e.getValue()); }

以下是一個從 HashMap 中檢索一組 Map.Entry 元素的示例 -

示例

 動態演示

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 s = hm.entrySet();
      Iterator iter = s.iterator();
      System.out.println("
Key\tValue"); while (iter.hasNext()) { Map.Entry e = (Map.Entry) iter.next(); System.out.println(e.getKey() + " " + e.getValue()); } } }

輸出

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

KeyValue
Backpack 1200
Belt 600
Wallet 700

更新於: 2019 年 7 月 30 日

284 次瀏覽

開始你的 職業

完成課程以獲得證書

開始
廣告
© . All rights reserved.