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