Iterating a Map means visiting each key-value pair it contains — printing them, transforming them, summing values, or building a new structure from them. Unlike a List which gives you a single element per step, each step through a Map gives you both a key and its associated value. Java provides three main approaches: forEach() for compact lambdas, entrySet().iterator() when you need remove-during-iteration, and an enhanced for loop over entrySet() for readable code without lambdas.

The forEach() method is the most concise option. It accepts a java.util.function.BiConsumer — a functional interface that receives two arguments (the key and the value) — which you can pass as a lambda expression.

public static void iterateUsingForEachLoop() { Map<String, String> map = Map.of("Item 1","Tomatoes", "Item 2","Oranges"); map.forEach((key, value)->System.out.println("Key : "+ key + " , Value : "+value)); }

When you run above program, you will get the following output.

Key : Item 1 , Value : Tomatoes
Key : Item 2 , Value : Oranges

You can obtain EntrySet by calling entrySet() method on Map, and obtain Iterator by calling iterator() on EntrySet.

public static void iterateViaEntrySetIterator() { Map<String, String> map = Map.of("Item 1","Tomatoes", "Item 2","Oranges"); Iterator<Map.Entry<String, String>> ite = map.entrySet().iterator(); while(ite.hasNext()) { Map.Entry<String, String> entry = ite.next(); System.out.println("Key : "+ entry.getKey() + " , Value : "+entry.getValue()); } }

When you run above program, you will get the following output.

Key : Item 1 , Value : Tomatoes
Key : Item 2 , Value : Oranges

You can obtain EntrySet by calling entrySet() method on Map, and then you iterate through EntrySet.

public static void iterateViaEntrySetEnhancedForLoop() { Map<String, String< map = Map.of("Item 1","Tomatoes", "Item 2","Oranges"); for(Map.Entry<String, String< entry: map.entrySet()) { System.out.println("Key : "+ entry.getKey() + " , Value : "+entry.getValue()); } }

When you run above program, you will get the following output.

Key : Item 1 , Value : Tomatoes
Key : Item 2 , Value : Oranges

Similar Articles

  1. How to remove elements from a Map