In this post, I am going explain the two approaches to iterate over a map using for-each loop.
Approach 1: for-each loop with Map entrySet
for (Map.Entry<Integer, String> entry : numbersMap.entrySet()) {
	System.out.printf("%d --> %s\n", entry.getKey(), entry.getValue());
}
Approach 2L for-each loop with Map keyset.
for (Integer key : numbersMap.keySet()) {
	System.out.printf("%d --> %s\n", key, numbersMap.get(key));
}
Find the below working application.
ForEachMapDemo.java
package com.sample.app;
import java.util.HashMap;
import java.util.Map;
public class ForEachMapDemo {
	public static void main(String[] args) {
		Map<Integer, String> numbersMap = new HashMap<>();
		numbersMap.put(1, "One");
		numbersMap.put(2, "Two");
		numbersMap.put(3, "Three");
		// Approach 1
		for (Map.Entry<Integer, String> entry : numbersMap.entrySet()) {
			System.out.printf("%d --> %s\n", entry.getKey(), entry.getValue());
		}
		System.out.println("\n\n");
		// Approach 2
		for (Integer key : numbersMap.keySet()) {
			System.out.printf("%d --> %s\n", key, numbersMap.get(key));
		}
	}
}
Output
1 --> One 2 --> Two 3 --> Three 1 --> One 2 --> Two 3 --> Three
    
 You may like
How to resolve NoClassDefFoundError?
Get the length of longest row in a two dimensional jagged array in Java
No comments:
Post a Comment