如何迭代<String,POJO>的地图?

Jim*_*mmy 1 java hashmap map pojo

我有一个Map<String, Person>(实际上我使用的是更复杂的POJO,但为了我的问题而简化它)

Person 好像 :

class Person
{
  String name;
  Integer age;

  //accessors
}
Run Code Online (Sandbox Code Playgroud)

如何遍历此地图,打印出密钥,然后是人名,然后是人员年龄,例如:

System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c));
Run Code Online (Sandbox Code Playgroud)
  • A是Map < String,Person> 的关键
  • B是Person.getName()的名字
  • C是来自Person.getAge()的年龄

我可以使用.values()从地图中提取所有值,详见HashMap文档,但我有点不确定如何获取密钥

Jig*_*shi 9

那么entrySet()怎么样

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());

}
Run Code Online (Sandbox Code Playgroud)