Java Map 的三种遍历方式

时间:2022-10-29 15:41:43

第一种是遍历 map中键所对应的值
public static void work(Map<String, Student> map) {
        Collection<Student> c = map.values();
        Iterator it = c.iterator();
        for (; it.hasNext();) {
            System.out.println(it.next());
        }
    }


第二种是遍历 map中的 键 和 值
public static void workByKeySet(Map<String, Student> map) {
        Set<String> key = map.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            System.out.println(map.get(s));
        }
    }

第三种和第二种差不多,但是比较灵活
 public static void workByEntry(Map<String, Student> map) {
        Set<Map.Entry<String, Student>> set = map.entrySet();
        for (Iterator<Map.Entry<String, Student>> it = set.iterator(); it.hasNext();) {
            Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next();
            System.out.println(entry.getKey() + "--->" + entry.getValue());
        }
    }
}