zoukankan      html  css  js  c++  java
  • JAVA遍历map的几种方式

    public static void main(String args[]) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("a", "A");
      map.put("b", "B");
      map.put("c", "C");
      // keySet遍历
      Iterator<String> iterator = map.keySet().iterator();
      while (iterator.hasNext()) {
        String key = iterator.next();
        String value = (String) map.get(key);
        System.out.println(value);
      }
      for (String key : map.keySet()) {
        String value = (String) map.get(key);
        System.out.println(value);
      }
      // entrySet遍历
      Iterator<Entry<String, Object>> iterator1 = map.entrySet().iterator();
      while (iterator1.hasNext()) {
        String value = (String) iterator1.next().getValue();
        System.out.println(value);
      }

      for (Entry<String, Object> entry : map.entrySet()) {
        String value = (String) entry.getValue();
        System.out.println(value);
      }
      //
      for (Object str : map.values()) {
        System.out.println(str);
      }
    }

    关于效率问题:

     如果你使用HashMap

    1. 同时遍历key和value时,keySet与entrySet方法的性能差异取决于key的具体情况,如复杂度(复杂对象)、离散度、冲突率等。换言之,取决于HashMap查找value的开销。entrySet一次性取出所有key和value的操作是有性能开销的,当这个损失小于HashMap查找value的开销时,entrySet的性能优势就会体现出来。例如上述对比测试中,当key是最简单的数值字符串时,keySet可能反而会更高效,耗时比entrySet少10%。总体来说还是推荐使用entrySet。因为当key很简单时,其性能或许会略低于keySet,但却是可控的;而随着key的复杂化,entrySet的优势将会明显体现出来。当然,我们可以根据实际情况进行选择
    2. 只遍历key时,keySet方法更为合适,因为entrySet将无用的value也给取出来了,浪费了性能和空间。在上述测试结果中,keySet比entrySet方法耗时少23%。
    3. 只遍历value时,使用vlaues方法是最佳选择,entrySet会略好于keySet方法。

    如果你使用TreeMap

    1. 同时遍历key和value时,与HashMap不同,entrySet的性能远远高于keySet。这是由TreeMap的查询效率决定的,也就是说,TreeMap查找value的开销较大,明显高于entrySet一次性取出所有key和value的开销。因此,遍历TreeMap时强烈推荐使用entrySet方法。
  • 相关阅读:
    ffmpeg 合并文件
    win10 设备摄像头,麦克风,【隐私】权限
    负载均衡,过载保护 简介
    《用Python做科学计算》 书籍在线观看
    Getting Started with OpenMP
    Algorithms & Data structures in C++& GO ( Lock Free Queue)
    PostgreSQL新手入门
    Ubuntu 网络配置
    QT 4.7.6 驱动 罗技C720摄像头
    使用vbs脚本添加域网络共享驱动器
  • 原文地址:https://www.cnblogs.com/systemEsc/p/3517551.html
Copyright © 2011-2022 走看看