你的位置:首页 > Java教程

[Java教程]遍历map的常用方法


Map< String, String> map = new HashMap<String, String>();
  map.put("a", "a1");
  map.put("b", "b1");
  map.put("c", "c1");
 1. for (String key : map.keySet()) {
   System.out.println("key = " + key + " and value = "+ map.get(key));
  }

2.Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
  while (iterator.hasNext()) {
   Map.Entry<java.lang.String, java.lang.String> entry = (Map.Entry<java.lang.String, java.lang.String>) iterator
     .next();
   System.out.println("key = " + entry.getKey() + " and value = "+ entry.getValue());
  }

//第三种:推荐,尤其是容量大时
  System.out.println("通过Map.entrySet遍历key和value");
  for (Map.Entry<String, String> entry : map.entrySet()) {
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
  }