map的三种遍历
public class MapTest { public static void main(String args[]){ Map<String, Integer> map = new HashMap<>(); List list =new ArrayList<>(); System.out.println(list.size()); map.put("1", 1); map.put("2", 2); map.put("3", 3); map.put("4", 4);
//采用keyset()迭代器 Iterator iterator =map.keySet().iterator(); while (iterator.hasNext()) { Object key= iterator.next(); System.out.println("key: "+key + "值为:"+map.get(key)); } Object key; Object value;
//采用entryset()迭代 Iterator iterator2=map.entrySet().iterator(); while (iterator2.hasNext()) { Map.Entry entry = (Map.Entry) iterator2.next(); key = entry.getKey(); value=entry.getValue(); System.out.println("key:"+key +"value:"+value); } System.out.println();
//采用foreach for (String key1 : map.keySet()) { System.out.println("key1:"+key1 + "value :"+map.get(key1)); } } }