Learn Java , Selenium

Please see below code for Iterating HashMap

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

public class Program2 {

	public static void main(String[] args) {

		HashMap<String, String> country_capital = new HashMap<String, String>();
		country_capital.put("India", "Delhi");
		country_capital.put("USA", "Washington DC");
		country_capital.put("China", "Bejing");
		country_capital.put("Russia", "Moscow");
		
		
		 for (Map.Entry<String, String> set :
			 country_capital.entrySet()) {
 
            // Printing all elements of a Map
            System.out.println(set.getKey() + " = "+ set.getValue());
                               
        }
	}

}

				
			

🧠 Output:

China = Bejing
Russia = Moscow
USA = Washington DC
India = Delhi


⚠️ Note: The order may change every time because HashMap does not maintain insertion order.

🧠 Explanation:


country_capital.entrySet() returns a set of all Map.Entry objects.

Each Map.Entry contains:

.getKey() → the country

.getValue() → the capital

✅ This is the standard way to loop through a HashMap.
If you want to maintain insertion order, you can replace HashMap with LinkedHashMap:

import java.util.LinkedHashMap;

LinkedHashMap<String, String> country_capital = new LinkedHashMap<>();

Scroll to Top