zoukankan      html  css  js  c++  java
  • 遍历Map的四种方法

     1         Map<String, Object> map = new HashMap<String, Object>();
     2         map.put("1", "csdn");
     3         map.put("2", "java");
     4         map.put("3", "PHP");
     5         map.put("4", 'c');
     6         map.put("5", 100);
     7 
     8         // 第一种:普遍使用,二次取值
     9         System.out.println("通过Map.keySet遍历key和value:");
    10         for (String key : map.keySet()) {
    11             System.out.println("key= " + key + " and value= " + map.get(key));
    12         }
    13 
    14         // 第二种
    15         System.out.println("通过Map.entrySet使用iterator遍历key和value:");
    16         Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
    17         while (it.hasNext()) {
    18             Map.Entry<String, Object> entry = it.next();
    19             System.out.println("key= " + entry.getKey() + " and value= "
    20                     + entry.getValue());
    21         }
    22 
    23         // 第三种:推荐,尤其是容量大时
    24         System.out.println("通过Map.entrySet遍历key和value");
    25         for (Map.Entry<String, Object> entry : map.entrySet()) {
    26             System.out.println("key= " + entry.getKey() + " and value= "
    27                     + entry.getValue());
    28         }
    29 
    30         // 第四种
    31         System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
    32         for (Object v : map.values()) {
    33             System.out.println("value= " + v);
    34         }
    35     
  • 相关阅读:
    类与对象
    类的声明与实例化
    面向对象的基本概念
    css下拉导航栏代码
    面向对象的三大特性
    面向对象三大基本特性,五大基本原则
    dom事件
    PHP 流程
    权限 查找
    留言板案例
  • 原文地址:https://www.cnblogs.com/wdpnodecodes/p/7418057.html
Copyright © 2011-2022 走看看