 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to loop through Map by Map.Entry
Create a Map and insert elements to in the form of key and value −
HashMap <String, String> map = new HashMap <String, String> (); map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); map.put("4", "D"); map.put("5", "E"); map.put("6", "F"); map.put("7", "G"); map.put("8", "H"); map.put("9", "I"); Now, loop through Map by Map.Entry. Here, we have displayed the key and value separately −
Set<Map.Entry<String, String>>s = map.entrySet(); Iterator<Map.Entry<String, String>>i = s.iterator(); while (i.hasNext()) {    Map.Entry<String, String>e = (Map.Entry<String, String>) i.next();    String key = (String) e.getKey();    String value = (String) e.getValue();    System.out.println("Key = "+key + " => Value = "+ value); } Example
import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class Demo {    public static void main(String[] args) {       HashMap<String, String>map = new HashMap<String, String>();       map.put("1", "A");       map.put("2", "B");       map.put("3", "C");       map.put("4", "D");       map.put("5", "E");       map.put("6", "F");       map.put("7", "G");       map.put("8", "H");       map.put("9", "I");       Set<Map.Entry<String, String>>s = map.entrySet();       Iterator<Map.Entry<String, String>>i = s.iterator();       while (i.hasNext()) {          Map.Entry<String, String>e = (Map.Entry<String, String>) i.next();          String key = (String) e.getKey();          String value = (String) e.getValue();          System.out.println("Key = "+key + " => Value = "+ value);       }    } }  Output
Key = 1 => Value = A Key = 2 => Value = B Key = 3 => Value = C Key = 4 => Value = D Key = 5 => Value = E Key = 6 => Value = F Key = 7 => Value = G Key = 8 => Value = H Key = 9 => Value = I
Advertisements
 