How to loop Map in Java

This article show few ways of loop Map in Java.

1. Using `entrySet()`

Before Java 8, this is the most common method to loop a Map in Java. We use the map’s entry set entrySet() to loop and access to each key-value pair.

LoopMap1.java

package com.mkyong.examples;

import java.util.HashMap;
import java.util.Map;

public class LoopMap1 {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Jan");
        map.put(2, "Feb");
        map.put(3, "Mar");

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
        }

    }

}

output


ID: 1, Name: Jan
ID: 2, Name: Feb
ID: 3, Name: Mar

2. Using `forEach` (Java 8 and later)

Java 8 introduced the forEach method, which provides a more simple way to iterate over maps using lambda expressions.

LoopMap2.java

package com.mkyong.examples;

import java.util.HashMap;
import java.util.Map;

public class LoopMap2 {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Jan");
        map.put(2, "Feb");
        map.put(3, "Mar");

        // map.forEach((key, value) -> System.out.println("ID: " + key + ", Name: " + value));

        map.forEach((id, name) -> {
            System.out.println("ID: " + id + ", Name: " + name);
        });


    }

}

output


ID: 1, Name: Jan
ID: 2, Name: Feb
ID: 3, Name: Mar

3. Using `stream()` (Java 8 and later)

We can use stream() to loop, filtering and collect in Java 8.

LoopMap3.java

package com.mkyong.examples;

import java.util.HashMap;
import java.util.Map;

public class LoopMap3 {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Jan");
        map.put(2, "Feb");
        map.put(3, "Mar");

        map.entrySet().stream()
                .forEach(entry -> System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()));

    }

}

output


ID: 1, Name: Jan
ID: 2, Name: Feb
ID: 3, Name: Mar

In below example, we use stream() to get the map’s entry if it’s value is equals to Jan.

LoopMap3.java

package com.mkyong.examples;

import java.util.HashMap;
import java.util.Map;

public class LoopMap3 {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Jan");
        map.put(2, "Feb");
        map.put(3, "Mar");

        map.entrySet().stream()
            .filter(entry -> "Jan".equals(entry.getValue()))
            .forEach(entry -> System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()));

        // Map stream, filter and collect to a Map. 
        /*
        Map<Integer, String> result = map.entrySet().stream()
                .filter(entry -> "Jan".equals(entry.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));*/


    }

}

output


ID: 1, Name: Jan

4. Using `iterator()`

The iterator did the jobs but not a common way to loop Map in Java.

LoopMap4.java

package com.mkyong.examples;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LoopMap4 {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Jan");
        map.put(2, "Feb");
        map.put(3, "Mar");

        // Map -> Set -> Iterator -> Map.Entry
        Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, String> entry = iterator.next();
            System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
        }

    }

}

5. Using `keySet()` and `get()`

This method involves iterating over the key set and then using each key to get its corresponding value. It’s slightly less efficient than using entrySet() because of the additional get() call. It might be useful for conditionally fetch values.

LoopMap5.java

package com.mkyong.examples;

import java.util.HashMap;
import java.util.Map;

public class LoopMap5 {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Jan");
        map.put(2, "Feb");
        map.put(3, "Mar");

        for (Integer key : map.keySet()) {
            System.out.println("Key : " + key + " Value : " + map.get(key));
        }

    }

}

6. References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments