Java中遍历Map的五种方式

  • Post author:
  • Post category:java

方法一:在for循环中遍历value

        Map<String, String> map = new HashMap();
        map.put("开发", "开发");
        map.put("测试", "测试");
        for (Object value : map.values()) {
            System.out.println("第一种:" + value);
        }

方法二::通过key遍历

        for (String key: map.keySet()) {
            System.out.println("第二种:" + map.get(key));
        }

方法三::通过entrySet实现遍历

		Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry entry : entrySet) {
            System.out.println("第三种:" + entry.getKey() + " :" + entry.getValue());
        }

方法四::通过Iterator迭代器实现遍历

        Iterator<Map.Entry<String, String>> entryIterator = map.entrySet().iterator();
        while (entryIterator.hasNext()) {
            Map.Entry<String, String> entry = entryIterator.next();
            System.out.println("第四种:" + entry.getKey() + " :" + entry.getValue());
        }

方法五 :通过lambda表达式进行遍历

        map.forEach((key, value) -> {
            System.out.println("第五种:" + key + " :" + value);
        });

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