###最常用,在键值都需要时使用。
Mapmap = new HashMap (); for (Map.Entry entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }复制代码
###在for-each循环中遍历keys或values。
Mapmap = new HashMap (); //遍历map中的键 for (Integer key : map.keySet()) { System.out.println("Key = " + key); } //遍历map中的值 for (Integer value : map.values()) { System.out.println("Value = " + value); }复制代码
###使用Iterator遍历
Mapmap = new HashMap (); Iterator > entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }复制代码
Map map = new HashMap(); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); Integer key = (Integer)entry.getKey(); Integer value = (Integer)entry.getValue(); System.out.println("Key = " + key + ", Value = " + value); }复制代码
###通过键找值遍历(效率低)
Mapmap = new HashMap (); for (Integer key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value);复制代码