How do I efficiently iterate over each entry in a Java Map?


If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?

Will the ordering of elements depend on the specific map implementation that I have for the interface?

The following is the Person POJO:

public class Person {
    private String name;
    private int age;
    public Person() {
    public Person(String name, int age) { = name;
        this.age = age;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public int getAge() {
        return age;
    public void setAge(int age) {
        this.age = age;
    public String toString() {
        return "Person{" + "name=" + name + ", age=" + age + '}';

The following is the Person Hashmap:

   public static void main(String[] args) {
        HashMap<Integer, Person> map = new HashMap();
        map.put(1, new Person("Eric Muchena", 25));
        map.put(2, new Person("David Muchena", 45));
        map.put(3, new Person("John Mark", 15));
        map.put(4, new Person("James Brian", 55));
        map.put(5, new Person("George Bush", 35));

2 Answers

Java has a utility class to iterate through a set. You can use the Iterator to loop through every entrySet() like this:

public static void printHashMap(HashMap map) {
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry);
            System.out.println(pair.getKey() + " = " + pair.getValue());
            it.remove(); // avoids a Concurrent Modification Exception

The following is the output:

You can use Java 8 Lambda expressions to print the content of a Java HashMap:

public static void printHashMap(HashMap map){
        map.entrySet().forEach((entry) -> {

The following is the output: