java如何遍历Map

1.利用map.keySet()普通遍历

public static void main(String[] args) {
        Map<Integer,String> map=new HashMap<>();
        map.put(1,"努力");
        map.put(2,"勤奋");
        map.put(3,"懒惰");
        for(Integer key:map.keySet()){
            System.out.println("key="+key+",value="+map.get(key));
        }
    }

2. 利用Iterator迭代器遍历

 public static void main(String[] args) {
        Map<Integer,String> map=new HashMap<>();
        map.put(1,"努力");
        map.put(2,"勤奋");
        map.put(3,"懒惰");
        Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, String> entry = it.next();
            System.out.println("key= " + entry.getKey() + ",value= " + entry.getValue());
        }
    }

3.利用map.entrySet()

 public static void main(String[] args) {
        Map<Integer,String> map=new HashMap<>();
        map.put(1,"努力");
        map.put(2,"勤奋");
        map.put(3,"懒惰");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
        }
    }

©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页