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

     1 public static void main(String[] args) {
     2 
     3    // 构建一个Map 初始值为3条数据
     4   Map<String, String> map = new HashMap<String, String>();
     5   map.put("1", "xiaqiu");
     6   map.put("2", "pangzi");
     7   map.put("3", "shouzi");
     8   
     9   //第一种:普遍使用,二次取值
    10   System.out.println("通过Map.keySet遍历key和value:");
    11   for (String key : map.keySet()) {
    12    System.out.println("key= "+ key + " and value= " + map.get(key));
    13   }
    14   
    15   //第二种:通过Iterator迭代器遍历循环Map.entrySet().iterator();
    16   System.out.println("通过Map.entrySet使用iterator遍历key和value:");
    17   Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
    18   while (it.hasNext()) {
    19    Map.Entry<String, String> entry = it.next();
    20    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    21   }
    22   
    23   //第三种:笔者推荐,尤其是容量大时(相对来说 比2好一点 效率高)
    24   System.out.println("通过Map.entrySet遍历key和value");
    25   for (Map.Entry<String, String> entry : map.entrySet()) {
    26    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    27   }
    28 
    29   //第四种
    30   System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
    31   for (String v : map.values()) {
    32    System.out.println("value= " + v);
    33   }
    34  }
  • 相关阅读:
    PHP获取汉字拼音首字母
    记录,待总结5
    HDU2833 WuKong Floyd
    搜索
    记录,待总结4
    HDU3350 #define is unsafe 栈的应用
    指针与引用的混合使用总结
    多源最短路径 Floyd
    引用总结
    函数返回值总结
  • 原文地址:https://www.cnblogs.com/XQiu/p/5087961.html
Copyright © 2011-2022 走看看