How can I iterate over a map of <String, POJO>?
我有一个
我如何迭代此地图,打印出密钥,然后是人名,然后是年龄,如:
- a是map
- b是来自person.getname()的名称
- c是来自person.getage()的年龄
我可以使用hashmap文档中详述的.values()从映射中提取所有值,但我有点不确定如何获取键
entryset()怎么样?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | HashMap<String, Person> hm = new HashMap<String, Person>(); 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<Map.Entry<String, Person>> set = hm.entrySet(); for (Map.Entry<String, Person> me : set) { System.out.println("Key :"+me.getKey() +" Name :"+ me.getValue().getName()+"Age :"+me.getValue().getAge()); } |
你可以使用:
- 映射.CasySyt()(如Org.Lovial.java所提到的)
- map.keyset(),如本例中所示(基于您的示例代码)
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Map<String, Person> personMap = ..... //assuming it's not null Iterator<String> 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)); } } |