如何迭代< String,POJO>? [英] How can I iterate over a map of <String, POJO>?
本文介绍了如何迭代< String,POJO>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Map< String,Person>
(实际上我正在使用一个更复杂的POJO,但为了我的问题简化了它)
I've got a Map<String, Person>
(actually I'm using a more complex POJO but simplifying it for the sake of my question)
Person
看起来像:
class Person
{
String name;
Integer age;
//accessors
}
我如何迭代这张地图,打印出关键字,然后是人名,然后人的年龄如:
How can I iterate through this map, printing out the key, then the person name, then the person age such as :
System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c));
- A是Map< String ,Person>
- B是Person.getName()的名称
- C是来自Person.getAge()的年龄
- A being the key from Map<String, Person>
- B being the name from Person.getName()
- C being the age from Person.getAge()
我可以使用.values()从地图中提取所有的值,详见 HashMap docs ,但我有点不确定如何获得密钥。 p>
I can pull all of the values from the map using .values() as detailed in the HashMap docs, but I'm a bit unsure of how I can get the keys
推荐答案
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());
}
这篇关于如何迭代< String,POJO>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文