java如何遍历Map

    技术2022-07-12  72

    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()); } }

    Processed: 0.010, SQL: 9