1 public class mapTest { 2 3 public static void main(String[] args) { 4 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 5 map.put(1, 1); 6 map.put(2, 2); 7 map.put(3, 3); 8 add1(map); 9 add2(map); 10 add3(map); 11 add4(map); 12 } 13 14 //循环map 15 public static Map<String,Object> add1(Map<Integer, Integer> map) { 16 for (Map.Entry<Integer, Integer> entry : map.entrySet()) { 17 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 18 } 19 return null; 20 } 21 22 //key value 单独取 23 public static Map<String,Object> add2(Map<Integer, Integer> map) { 24 for (Integer key : map.keySet()) { 25 System.out.println("Key = " + key); 26 } 27 //遍历map中的值 28 for (Integer value : map.values()) { 29 System.out.println("Value = " + value); 30 } 31 return null; 32 } 33 34 //使用Iterator遍历 35 public static Map<String,Object> add3(Map<Integer, Integer> map) { 36 Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); 37 while (entries.hasNext()) { 38 Map.Entry<Integer, Integer> entry = entries.next(); 39 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 40 } 41 return null; 42 } 43 44 public static Map<String,Object> add4(Map<Integer, Integer> map) { 45 for (Integer key : map.keySet()) { 46 Integer value = map.get(key); 47 System.out.println("Key = " + key + ", Value = " + value); 48 } 49 return null; 50 } 51 }
PS:如果仅需要键(keys)或值(values)使用方法二。如果你使用的语言版本低于java 5,或是打算在遍历时删除entries,必须使用方法三。否则使用方法一(键值都要)。