HashMap遍历方法总结

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapOperation {
    private static Map<String, String> map = new HashMap<String, String>();
    static {
        map.put("1", "value1");
        map.put("2", "value2");
        map.put("3", "value3");
        map.put("4", "value4");
    }
    public static void method() {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key : " + entry.getKey());
            System.out.println("value : " + entry.getValue());
        }
    }

    public static void method2() {
        for (String key : map.keySet()) {
            System.out.println("key : " + key);
            System.out.println("value : " + map.get(key));
        }
    }

    public static void method3() {
        Iterator<HashMap.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println("key : " + entry.getKey());
            System.out.println("value : " + entry.getValue());
        }
    }


    public static void method4() {
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            System.out.println("key : " + key);
            System.out.println("value : " + map.get(key));
        }
    }

    public static void method5() {
        map.forEach((key, value) -> {
            System.out.println("key : " + key);
            System.out.println("value : " + value);
        });
    }

    //通过Map.values()遍历所有的value,但不能遍历key"
    public static void method6() {
        for (String v : map.values()) {
            System.out.println("The value is " + v);
        }

    }

    public static void method7() {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key:" + entry.getKey());
            System.out.println(" Value:" + entry.getValue());
        }
    }
}

 

posted @ 2021-05-18 19:55  一名不断学习的程序猿  阅读(63)  评论(0)    收藏  举报