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));

現在,檢索所有值 −

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

輸出

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

Values...
1200
600
700

更新於: 30-07-2019

223 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.