1 package com.test; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 import java.util.Set; 7 8 /** 9 * Created by Donge on 2017/2/6. 10 */ 11 public class TestMap { 12 public static void main(String[] args) { 13 Map<Integer, String> map = new HashMap<>(); 14 map.put(1, "v1"); 15 map.put(2, "v2"); 16 map.put(3, "v3"); 17 // 方法一 推荐 18 for (Map.Entry e : map.entrySet()) { 19 System.out.println(e.getKey() + " : " + e.getValue()); 20 } 21 System.out.println("*************************"); 22 // 方法二 23 Set<Integer> keys = map.keySet(); 24 for (Integer k : keys){ 25 System.out.println(k+" : "+map.get(k)); 26 } 27 System.out.println("*************************"); 28 // 方法三 29 Iterator<Integer> iterator = map.keySet().iterator(); 30 while (iterator.hasNext()){ 31 Integer key = iterator.next(); 32 System.out.println(key+" : "+map.get(key)); 33 } 34 System.out.println("*************************"); 35 // 方法四 此方法不能获取key值 36 for (String v : map.values()){ 37 System.out.println(v); 38 } 39 } 40 }