Java Map Iterator Example

Java Map Overview

Map is an important Java collection implementation defined in java.util package, it is designed to store with key and value  element pairs. In this how-to example, let’s go over how to iterate over a map in Java.

Way 1: Iterate over a Map using Java Map Iterator.

Maps do not provide an iterator method as Lists and Sets do, but it provides two APIs keySet() and values(), the two APIs return a set view of keys or values contained in this Map, the idea using keyset() or values() is to get keys or values in collection container form and then be able to iterate over it, the following is Java Map iterator example code:
import java.util.*

public class IterateOverMapExample {
	public static void main(String[] args) {
                Map<String, String> maps = new HashMap<String, String>();
		maps.put("iterate map 1", "test string1");
		maps.put("iterate map 2", "test string2");
		maps.put("iterate map 3", "test string3");

		//Iterate over entrySet
		Set> entries = maps.entrySet();
		Iterator> iterator = entries.iterator();
		while (iterator.hasNext()) {
			Entry entry =;
			System.out.println("Key: " + entry.getKey() + "Value: "
					+ entry.getValue());

		//Iterate over values
		Collection values = maps.values();
		Iterator iterator2 = values.iterator();
		while (iterator2.hasNext()) {
			System.out.println("Value: " +;

Its a very common approach to iterate over a map, it allows you to safely remove an entry of map during iteration without any concurrent issues.

Way 2: Iterating over entries using For-Each loop.

If you are using JDK 1.5 or later, rather than using iterator, The alternative solution is to simply iterate over the keySet or values by using For-Each loop statement.

Map<String, String> maps = new HashMap<String, String>();

//iterating over keys only
for (Integer key : maps.keySet()) {
  System.out.println("Key = " + key);

//iterating over values only
for (Integer value : maps.values()) {
  System.out.println("Value = " + value);

I personally recommend that you do use way 2, it simplifies code and does not have a call to Java map entrySet iteration to avid the additional performance cost.

Оцените статью
Добавить комментарий

Your email address will not be published. Required fields are marked *



  1. jnab

    Way 2:
    Map maps

    why do we have Integer key then?
    should not it be of type String too?

    1. admin автор

      Yes, since your key is string therefore it should be of type string