How can I iterate over a map of <String, POJO>?
What about 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:
- Map.entrySet() (as mentioned by org.life.java) or,
- Map.keySet() as in this example (based on your sampled code)
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));
}
}