java如何遍历Map

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

public static void main(String[] args) {
        Map 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));
        }
    }

java如何遍历Map_第1张图片

2. 利用Iterator迭代器遍历

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

java如何遍历Map_第2张图片

3.利用map.entrySet()

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

java如何遍历Map_第3张图片

你可能感兴趣的:(Java)