Map的几种遍历方式


    public static void main(String[] args) {

        Map map = new HashMap<>();
        map.put("1", "a");
        map.put("2", "b");
        map.put("3", "c");
        map.put("4", "d");
        //遍历所有的键,根据键获取对应的值
        Set keySet = map.keySet();
        for (String key : keySet) {
            System.out.println("key = " + key + "=====> value = " + map.get(key));
        }
        //遍历所有的值
        Collection values = map.values();
        for (String value : values) {
            System.out.println("value = " + value);
        }
        //EntrySet遍历
        for (Map.Entry entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("key = " + key + "=====> value = " + value);
        }
        //Iterator遍历
        Iterator> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry next = iterator.next();
            String key = next.getKey();
            String value = next.getValue();
            System.out.println("key = " + key + "=====> value = " + value);
        }
        //forEach遍历(jdk1.8)
        map.forEach((key, value) -> {
            System.out.println("key = " + key + "=====> value = " + value);
        });

    }

 

你可能感兴趣的:(Map的几种遍历方式)