Monday, 6 February 2017

java - How can I iterate over a map of ?



I've got a Map (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


Answer



What about entrySet()



HashMap hm = new HashMap();

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> set = hm.entrySet();

for (Map.Entry me : set) {
System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...