如HashMap, TreeMap, ConcurrentHashMap等。
方法1: 使用Iterator遍历
1 2 3 4 5 6
| Map<Integer, Integer> map = new HashMap<>(); 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()); }
|
使用Iterator迭代map的一个优势是:在迭代过程中可以使用iterator.remover()正常删除map中的entry, 如果在for-each循环中删除entry,系统会报unpredictable resultes
异常。
方法2: for-each遍历map.entrySet()
1 2 3 4
| Map<Integer, Integer> map = new HashMap<>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
|
方法3: for-each遍历map.keySet(), map.values
1 2 3 4 5 6 7 8 9 10 11
| Map<Integer, Integer> map = new HashMap<>();
for (Integer key : map.keySet()) { System.out.println("Key = " + key); Integer value = map.get(key); System.out.println("Value = " + value); }
for (Integer value : map.values()) { System.out.println("Value = " + value); }
|