Java HashMap的三种遍历方式

package com.LeeG.work;

import java.util.*;

/**
 * @author LeeG
 * @date 2020/12/15 11:29
 */
public class Main {
    
    

    public static void main(String[] args) {
    
    
	    // write your code here
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "v1");
        map.put(2, "v2");
        map.put(3, "v3");

        /**
         * 第一种:通过Map.keySet()遍历
         * keySet()方法返回一个内部引用,并指向一个内部类对象,
         * 该内部类重写了迭代器方法,当在增强for循环时才调用,并从外部类的table中取值。
         */
        System.out.println("第一种: ");
        for (Integer key : map.keySet()) {
    
    
            System.out.println("key = " + key + " and value = " + map.get(key));
        }

        /**
         * 第二种:通过Map.entrySet使用iterator遍历key和value
         */
        System.out.println("第二种: ");
        Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
    
    
            Map.Entry<Integer, String> entry = it.next();
            System.out.println("key = " + entry.getKey() + " and value = " + entry.getValue());
        }

        /**
         * 第三种:通过Map.entrySet遍历key和value(推荐)
         * Map.entrySet() 这个方法返回的是一个Set<Map.Entry<K, V>>,Map.Entry是Map中的一个接口,
         * 他的用途是表示一个映射项(里面有key和value),而Set<Map.Entry<K, V>>表示一个映射项的Set。
         * Map.Entry里有相应的getKet和getValue方法,即JavaBean,让我们能够从一个项中取出Key和Value.
         */
        System.out.println("第三种: ");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
    
    
            System.out.println("key = " + entry.getKey() + " and value = " + entry.getValue());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44723496/article/details/112388595