How can I iterate over a map of <String, POJO>?

狂风中的少年 提交于 2019-11-26 10:04:41

问题


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 looks like :

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 being the key from Map<String, Person>
  • B being the name from Person.getName()
  • C being the age from Person.getAge()

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


回答1:


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());

}



回答2:


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));

    }
}


来源:https://stackoverflow.com/questions/3995463/how-can-i-iterate-over-a-map-of-string-pojo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!