我有一个Map<String, Person>
(实际上我使用的是更复杂的 POJO,但为了解决我的问题而简化了它)
Person
看起来像:
class Person
{
String name;
Integer age;
//accessors
}
我如何迭代这个 map ,打印出键,然后打印出人名,然后打印出人的年龄,例如:
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() 从 map 中提取所有值,如 HashMap docs 中详述。 ,但我有点不确定如何获得 key
最佳答案
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());
}
关于java - 如何迭代 <String, POJO> 的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3995463/