首页 > 其他 > 详细

HashMap遍历方法总结

时间:2021-05-18 23:17:42      阅读:33      评论:0      收藏:0      [点我收藏+]
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());
        }
    }
}

 

HashMap遍历方法总结

原文:https://www.cnblogs.com/freecodewriter/p/14782421.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!