Java Collection How to - Loop through Map by Map.Entry








Question

We would like to know how to loop through Map by Map.Entry.

Answer

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/*w  ww.jav a2  s  . com*/
public class Main {

  public static void main(String[] args) {
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("3", "three");
    hm.put("1", "one");
    hm.put("4", "four");
    hm.put("2", "two");
    printMap(hm);
  }

  public static void printMap(Map<String, String> map) {
    Set<Map.Entry<String, String>> s = map.entrySet();
    Iterator<Map.Entry<String, String>> it = s.iterator();
    while (it.hasNext()) {
      Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
      String key = (String) entry.getKey();
      String value = (String) entry.getValue();
      System.out.println(key + " => " + value);
    }
  }
}

The code above generates the following result.