Map 的 5 种遍历方式

Map 的 5 种遍历方式

强烈推荐 for-each + entrySet()遍历lambda 表达式遍历 ,简洁又好用!!!

package com.maptest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapTest {
    
    /**
     * Map 的 5 种遍历方式
     * @param args
     */
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("张三", "zhangsan");
        map.put("李四", "lisi");
        map.put("王五", "wangwu");

        // 1.for-each + keySet()遍历
        Set<String> keySet = map.keySet();
        for (String key : keySet) { //遍历key
            System.out.println(key + " :keySet: " + map.get(key));
        }

        // 2.for-each + entrySet()遍历(强烈推荐)
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey()+ " :entrySet: " + entry.getValue());
        }

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

        // 4.lambda 表达式遍历(强烈推荐)
        map.forEach((key, value) -> {
            System.out.println(key + " :lambda: " + value);
        });

        // 5.stream流 + entrySet 遍历
        map.entrySet().stream().forEach((Map.Entry<String, String> entry) -> {
            System.out.println(entry.getKey() + " :stream: " + entry.getValue());
        });
    }
}

你可能感兴趣的:(java,开发语言)