Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...