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[]) {
//创建哈希映射
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("\nKeys...");
Set keys = hm.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
System.out.println("\nValues...");
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热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短