HashMap的四种遍历方式

HashMap的四种遍历方式

package com.learning.java;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapTest {

    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();

        map.put("k1", 1);
        map.put("k2", 2);
        map.put("k3", 3);

        //遍历方式1:利用Map.Entry
        for (Map.Entry<String, Integer> m : map.entrySet()) {
            String k = m.getKey();
            int v = m.getValue();
            System.out.println("key = " + k + ",value = " + v);
        }
        System.out.println("---------------------------");

        //遍历方式2 利用iterator
        Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Integer> next = it.next();
            String k = next.getKey();
            int v = next.getValue();
            System.out.println("key = " + k + ",value = " + v);
        }
        System.out.println("---------------------------");

        //遍历方式3 利用map.keySet 通过k获取v
        for (String k : map.keySet()) {
            int v = map.get(k);
            System.out.println("key = " + k + ",value = " + v);
        }
        System.out.println("---------------------------");

        //遍历方式4 jdk1.8特有
        map.forEach((k, v) -> {
            System.out.println("key = " + k + ",value = " + v);
        });

    }
}
posted @ 2021-11-21 16:16  zzjane摆大烂  阅读(30)  评论(0编辑  收藏  举报