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     
  • 相关阅读:
    poj1830 开关问题
    poj1681 Painter's Problem
    poj1222 EXTENDED LIGHTS OUT
    bzoj1923 [Sdoi2010]外星千足虫
    bzoj1013 [JSOI2008]球形空间产生器sphere
    poj2888 Magic Bracelet
    poj2409 Let it Bead
    poj1286 Necklace of Beads
    bzoj1004 HNOI2008 Cards
    bzoj2040 [2009国家集训队]拯救Protoss的故乡
  • 原文地址:https://www.cnblogs.com/wdpnodecodes/p/7418057.html
Copyright © 2011-2022 走看看