[英]How can I iterate over a map of <String, 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) 我有一个
Map<String, Person>
(实际上,我在使用一个更复杂的POJO,但是为了我的问题而简化了它)
Person
looks like : 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));
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 我可以使用HashMap文档中详细介绍的.values()从地图中提取所有值,但是我不确定如何获取键
What about entrySet() 那么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());
}
You can use: 您可以使用:
Example: 例:
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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.