如何迭代的地图?
我有一个Map
(实际上我正在使用更复杂的POJO,但为了我的问题而简化它)
Person
看起来像:
class Person { String name; Integer age; //accessors }
如何遍历此地图,打印出密钥,然后是人名,然后是人员年龄,例如:
System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c));
- A是Map < String ,Person>的关键
- B是Person.getName()的名字
- C是来自Person.getAge()的年龄
我可以使用.values()从地图中提取所有值,详见HashMap文档 ,但我有点不确定如何获取密钥
那么entrySet()怎么样
HashMap hm = new HashMap(); hm.put("A", new Person("p1")); hm.put("B", new Person("p2")); hm.put("C", new Person("p3")); hm.put("D", new Person("p4")); hm.put("E", new Person("p5")); Set> set = hm.entrySet(); for (Map.Entry me : set) { System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge()); }
您可以使用:
- Map.entrySet() (如org.life.java所述)或者,
- Map.keySet(),如本例所示(基于您的采样代码)
例:
Map personMap = ..... //assuming it's not null Iterator strIter = personMap.keySet().iterator(); synchronized (strIter) { while (strIter.hasNext()) { String key = strIter.next(); Person person = personMap.get(key); String a = key; String b = person.getName(); String c = person.getAge().toString(); System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c)); } }