Map常用的几种遍历方式

本文来说下Map常用的几种遍历方式

文章目录


程序实例

程序实例

package util;

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

/***
 * Map常用的
 * 几种遍历方式
 */
public class MapCirculate {

    public static void main(String[] args) {

        Map<String, String> tempMap = new HashMap<>();
        tempMap.put("a","12");
        tempMap.put("b","34");
        tempMap.put("c","56");

        // JDK1.4中
        // 遍历方法一 hashmap entrySet() 遍历
        Iterator it = tempMap.entrySet().iterator();
        while (it.hasNext()) {

            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            System.out.println("key=" + key + " value=" + value);
        }

        System.out.println("=========================");

        // JDK1.5中,应用新特性For-Each循环
        // 遍历方法二
        for (Map.Entry<String, String> entry : tempMap.entrySet()) {

            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("key=" + key + " value=" + value);
        }

        System.out.println("=========================");

        // 遍历方法三 hashmap keySet() 遍历
        for (Iterator i = tempMap.keySet().iterator(); i.hasNext();) {

            Object obj = i.next();
            System.out.println("key=" + obj + " value=" + tempMap.get(obj));
        }

        System.out.println("=========================");

        // 遍历方法四 treemap keySet()遍历
        for (Object o : tempMap.keySet()) {
            System.out.println("key=" + o + " value=" + tempMap.get(o));
        }

        System.out.println("=========================");

        //5.通过Lambda表达式的方式遍历Map
        tempMap.forEach((key,value)->{
            System.out.println("key="+key+",value="+value);
        });

        System.out.println("=========================");

        //或
        tempMap.forEach((key,value)-> System.out.println("key="+key+",value="+value) );
        //只有一行代码可以省略大括号{}

    }
}

程序结果

在这里插入图片描述


版权声明:本文为qq_31960623原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。