方法一:在for-each循环中使用entries来遍历
1 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 2 3 for (Map.Entry<Integer, Integer> entry : map.entrySet()) { 4 5 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 6 7 }
方法二:使用Iterator遍历
1 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 2 3 Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); 4 5 while (entries.hasNext()) { 6 7 Map.Entry<Integer, Integer> entry = entries.next(); 8 9 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 10 11 }
该方法还设计到一种设计模式,即迭代模式。该方法可以在遍历时调用iterator.remove()来删除entries。
也可以不加入泛型:
1 Map map = new HashMap(); 2 3 Iterator entries = map.entrySet().iterator(); 4 5 while (entries.hasNext()) { 6 7 Map.Entry entry = (Map.Entry) entries.next(); 8 9 Integer key = (Integer)entry.getKey(); 10 11 Integer value = (Integer)entry.getValue(); 12 13 System.out.println("Key = " + key + ", Value = " + value); 14 15 }
方法三 通过键集合遍历值
1 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 2 3 for (Integer key : map.keySet()) { 4 5 Integer value = map.get(key); 6 7 System.out.println("Key = " + key + ", Value = " + value); 8 9 }
该方法效率很低,不推荐使用
方法四 values()方法
1 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 2 3 4 for (Integer key : map.keySet()) { 5 6 System.out.println("Key = " + key); 7 8 } 9 10 for (Integer value : map.values()) { 11 12 System.out.println("Value = " + value); 13 14 }
时间: 2024-11-05 14:56:25