zoukankan      html  css  js  c++  java
  • java之map遍历

    java开发中常常会用到遍历,所以下边就列举四种map的遍历方法。

    public class testMap {
    
        public static void main(String[] args) {
            Map<Object, Object> map = new HashMap<Object, Object>();
            map.put("01", "A");
            map.put("02", "B");
            map.put("03", "C");
    //        test1(map);
    //        test2(map);
    //        test3_1(map);
    //        test3_2(map);
            test4(map);
        }
    
        /**
         * 遍历map方法一
         * 
         * @param map
         */
        public static void test1(Map<Object, Object> map) {
            for (Entry<Object, Object> entry : map.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = "
                        + entry.getValue());
            }
        }
    
        /**
         * 遍历map方法二
         * 
         * @param map
         */
        public static void test2(Map<Object, Object> map) {
            // 遍历map中的键
            for (Object key : map.keySet()) {
                System.out.println("Key = " + key);
            }
    
            // 遍历map中的值
            for (Object value : map.values()) {
                System.out.println("Value = " + value);
            }
        }
    
        /**
         * 遍历map方法三(非泛型)
         * 
         * @param map
         */
        public static void test3_1(Map<Object, Object> map) {
            Iterator<Entry<Object, Object>> entries = map.entrySet().iterator();
            Entry<Object, Object> entry;
            while (entries.hasNext()) {
                entry = entries.next();
                System.out.println("Key = " + entry.getKey() + ", Value = "
                        + entry.getValue());
            }
        }
    
        /**
         * 遍历map方法三(泛型)
         * 
         * @param map
         */
        public static void test3_2(Map<Object, Object> map) {
            Iterator entries = map.entrySet().iterator();
            Entry entry;
            while (entries.hasNext()) {
                entry = (Entry) entries.next();
                System.out.println("Key = " + entry.getKey() + ", Value = "
                        + entry.getValue());
            }
        }
    
        /**
         * 遍历map方法四
         * 
         * @param map
         */
        public static void test4(Map<Object, Object> map) {
            for (Object key : map.keySet()) {
                System.out.println("Key = " + key + ", Value = " + map.get(key));
            }
        }
    }
  • 相关阅读:
    Spring MVC源码——Root WebApplicationContext
    ThreadPoolExecutor 源码阅读
    Spark RDD
    HashMap 源码阅读
    不定期更新的IDEA功能整理
    Jvm内存区域和GC
    装饰模式和Java IO
    spring websocket集群问题的简单记录
    Kotlin in Action 笔记
    WebSphere部署Spring Boot
  • 原文地址:https://www.cnblogs.com/lidelin/p/11772235.html
Copyright © 2011-2022 走看看