检索HashMap中所有键的集合的Java程序
首先,创建一个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(); System.out.println("\nKeys..."); Iterator i = keys.iterator(); while (i.hasNext()) { System.out.println(i.next()); }
下面以获取HashMap中所有key的集合为例
示例
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); Set keys = hm.keySet(); System.out.println("\nKeys..."); Iterator i = keys.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }
以下是输出
Map = {Backpack=1200, Belt=600, Wallet=700} Keys... Backpack Belt Wallet