遍历Java中HashMap的值

使用Iterator迭代HashMap的值-

HashMap hm = new HashMap();
//将元素放入映射
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));

现在,使用Iterator来显示每个值和键-

//获取一个迭代器
Iterator i = set.iterator();
//显示元素
while(i.hasNext()) {
   Map.Entry me = (Map.Entry)i.next();
   System.out.print(me.getKey() + ": ");
   System.out.println(me.getValue());
}

以下是迭代HashMap的值的示例-

示例

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      //创建一个哈希映射
      HashMap hm = new HashMap();
      //将元素放入映射
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      Set set = hm.entrySet();
      System.out.println("HashMap中的元素...-");
      //获取一个迭代器
      Iterator i = set.iterator();
      //显示元素
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
   }
}

输出结果

HashMap中的元素...-
Frames: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000