HashMap遍历方式

HashMap中提供了获取entrySet、keySet、values的方法,可以通过foreach或者迭代器Iterator来获取其中的值,其中两种foreach循环的原理一样。

public class Traversal {

    public static void main(String[] args) {
        Traversal t = new Traversal();
        Map map = t.initHashMap();
        t.method1(map);
    }

    private Map initHashMap() {
        Map map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        map.put("key4", "value4");
        map.put("key5", "value5");
        return map;
    }

    /**
     * 通过entrySet遍历
     *
     * @param map 参数
     */
    private void method1(Map map) {
        for (Map.Entry entry : map.entrySet()) {
            System.out.println(entry.getKey() + "," + entry.getValue());
        }

        map.forEach((k, v) -> System.out.println(k + "," + v));

        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            System.out.println(entry.getKey() + "," + entry.getValue());
        }
    }

    /**
     * 通过keySet遍历
     *
     * @param map 参数
     */
    private void method2(Map map) {
        for (String key : map.keySet()) {
            System.out.println(key + "," + map.get(key));
        }

        map.keySet().forEach((k) -> System.out.println(k + "," + map.get(k)));

        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            System.out.println(key + "," + map.get(key));
        }
    }

    /**
     * 通过values遍历
     *
     * @param map 参数
     */
    private void method3(Map map) {
        for (String value : map.values()) {
            System.out.println(value);
        }

        map.values().forEach(System.out::println);

        Iterator<String> it = map.values().iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

}

你可能感兴趣的:(Java)