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

    在java中所有的map都实现了Map接口,因此所有的Map(如HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以用以下的方式去遍历。

    方法一:在for循环中使用entries实现Map的遍历(最常用的):

      /**
      * 最常见也是大多数情况下用的最多的,一般在键值对都需要使用
      */
      Map <String,String>map = new HashMap<String,String>();
        map.put("one", "我是第一名");
        for(Map.Entry<String, String> entry : map.entrySet()){
          String mapKey = entry.getKey();
          String mapValue = entry.getValue();
          System.out.println(mapKey+":"+mapValue);
        }

    方法二:在for循环中遍历key或者values,只需要map中的key或者value时使用,在性能上比使用entrySet较好;

      Map <String,String>map = new HashMap<String,String>();
        map.put("one", "我是第一名");
        //key
        for(String key : map.keySet()){
          System.out.println(key);
         }
        //value
        for(String value : map.values()){
          System.out.println(value);
        }

    方法三:通过Iterator遍历(增强for循环原理也是Iterator);

    Iterator<Entry<String, String>> entries = map.entrySet().iterator();
      while(entries.hasNext()){

        //先next在获取,否则会空指针
        Entry<String, String> entry = entries.next();
        String key = entry.getKey();
        String value = entry.getValue();
        System.out.println(key+":"+value);
      }

    方法四:通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作;

    for(String key : map.keySet()){
        String value = map.get(key);
        System.out.println(key+":"+value);
    }
  • 相关阅读:
    设置网页内容不准复制
    a标签打电话
    <base target="_blank" />
    常用sql语句 DML语句
    常用sql-----DDL语句
    php文件操作
    php格式化时间
    php 数组函数
    程序员和特种兵 几分相似几分无奈
    女码农的真实生活:程序“媛”无法卖萌
  • 原文地址:https://www.cnblogs.com/lzghyh/p/11899463.html
Copyright © 2011-2022 走看看