七种遍历Map的方法

七种遍历Map的方法

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

public class Wan {
    public static void main(String[] args) {
        Map<String,String> dataMap = new HashMap<>();
        dataMap.put("A","Abb");
        dataMap.put("B","Bcc");
        dataMap.put("C","Cdd");


        // 1. forEach+lambda
        dataMap.forEach((k,v)-> System.out.println(k+"->"+v));

        // 2. keySet+foreach
        for (String key: dataMap.keySet()){
            System.out.println(key+"->"+dataMap.get(key));
        }

        // 3. entry+stream
        dataMap.entrySet().stream().forEach(entry ->
                System.out.println(entry.getKey()+"->"+entry.getValue())
        );

        // 4. stream并行处理
        dataMap.entrySet().stream().parallel().forEach(entry ->
                System.out.println(entry.getKey()+"->"+entry.getValue())
        );

        // 5. foreach Map.EntrySet
        for (Map.Entry<String,String> item: dataMap.entrySet()) {
            System.out.println(item.getKey()+"->"+item.getValue());
        }

        // 6.迭代器+Map.Entry
        Iterator<Map.Entry<String,String>> item2 = dataMap.entrySet().iterator();
        while (item2.hasNext()){
            Map.Entry<String,String> next = item2.next();
            System.out.println(next.getKey()+"->"+next.getValue());
        }

        // 7. keyset+迭代器
        Iterator<String> item3 = dataMap.keySet().iterator();
        while (item3.hasNext()){
            String key = item3.next();
            System.out.println(key+"->"+dataMap.get(key));
        }
        
    }
}

你可能感兴趣的:(Java,java)