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[]) { // 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); System.out.println("
Keys..."); Set keys = hm.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { System.out.println(i.next()); } System.out.println("
Values..."); 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
广告