方式一 這是最多見的而且在大多數狀況下也是最可取的遍歷方式。在鍵值都須要時使用。code
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
方法二 在for-each循環中遍歷keys或values。get
若是隻須要map中的鍵或者值,你能夠經過keySet或values來實現遍歷,而不是用entrySet。it
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //遍歷map中的鍵 for (Integer key : map.keySet()) { System.out.println("Key = " + key); } //遍歷map中的值 for (Integer value : map.values()) { System.out.println("Value = " + value); }
方法三使用Iterator遍歷效率
使用泛型:泛型
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, Integer> 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); }
方法4、經過鍵找值遍歷(效率低)遍歷
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Integer key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value);