三种遍历HashMap的方法

public class TraverseMapTest {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("k1","v1");
        map.put("k2","v2");
        map.put("k3","v3");
        //1.keySet
        for(String str : map.keySet()){
            System.out.println("K:"+str+"  V:"+map.get(str));
        }
        //2.EntrySet
        for(Map.Entry en: map.entrySet()){
            System.out.println("K:"+en.getKey()+"  V:"+en.getValue());
        }
        //3.EntrySet的Iterator方法
        Iterator> it = map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry = it.next();
            System.out.println("K:"+entry.getKey()+"  V:"+entry.getValue());
        }

    }


}

你可能感兴趣的:(三种遍历HashMap的方法)