遍历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
热门推荐
10 對好友毕业祝福语简短
11 女宝宝满月简短祝福语
12 朋友搬迁新房祝福语简短
13 好姐妹生日祝福语 简短
14 同学道别祝福语简短
15 亲戚送行祝福语简短精辟
16 对同学祝福语 简短独特
17 孩子满月随礼简短祝福语
18 给老师祝福语简短元旦