• 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));
            }
        }
    }
  • 相关阅读:
    jsp完成页面自动刷新
    ssm整合案例
    MySql 里的IFNULL、NULLIF和ISNULL用法
    数据库优化
    数据库读写并发控制
    solr入门
    AngularJS入门(一)
    jsp和html的的区别
    Docker 网络(十一)
    Docker 容器资源隔离 namespace(十)
  • 原文地址:https://www.cnblogs.com/lidelin/p/11772235.html
Copyright © 2020-2023  润新知