zoukankan      html  css  js  c++  java
  • Java之Map遍历方式性能分析:ketSet与entrySet

    keySet():将Map中所有的键存入到Set集合中。因为set具备迭代器,所以可以以迭代方式取出所有的键,再根据get方法获取每一个键对应的值,其仅能通过get()取key。
    entrySet(): 返回此映射中包含的映射关系的 Set 视图,格式为Set<Map.Entry<K,V>>, Map.Entry表示映射关系,迭代后可以e.getKey()、e.getValue()取key和value,返回的是Entry接口 。 
    keySet()方式
    Set<String> keySet = map.keySet();//先获取map集合的所有键的Set集合
    Iterator<String> it = keySet.iterator();//有了Set集合,就可以获取其迭代器
    while (it.hasNext()) {
    String key = it.next();
    String value = map.get(key);//有了键可以通过map集合的get方法获取其对应的值。
    }
    entrySet()方式: 
    //通过entrySet()方法将map集合中的映射关系取出(这个关系就是Map.Entry类型)
    Set<Map.Entry<String, String>> entrySet = map.entrySet();
    //将关系集合entrySet进行迭代,存放到迭代器中
    Iterator<Map.Entry<String, String>> it2 = entrySet.iterator();
    while (it2.hasNext()) {
    Map.Entry<String, String> me = it2.next();//获取Map.Entry关系对象me
    String key2 = me.getKey();//通过关系对象获取key
    String value2 = me.getValue();//通过关系对象获取value
    }
    性能测试:
    public static void main(String[] args) {
    HashMap<String, String> keySetMap = new HashMap<String, String>();
    HashMap<String, String> entrySetMap = new HashMap<String, String>();
    for (int i = 0; i < 100000; i++) {
    keySetMap.put("" + i, "keySet");
    entrySetMap.put("" + i, "entrySet");
    }
    long startTimeOne = System.currentTimeMillis();
    Iterator<String> keySetIterator = keySetMap.keySet().iterator();
    while (keySetIterator.hasNext()) {
    String key = keySetIterator.next();
    String value = keySetMap.get(key);
    System.out.println(key + "," + value);
    }
    System.out.println("keyset spent times:" + (System.currentTimeMillis() - startTimeOne));

    long startTimeTwo = System.currentTimeMillis();
    Iterator<Map.Entry<String, String>> entryKeyIterator = entrySetMap.entrySet().iterator();
    while (entryKeyIterator.hasNext()) {
    Map.Entry<String, String> e = entryKeyIterator.next();
    System.out.println(e.getKey() + "," + e.getValue());
    }
    System.out.println("entrySet spent times:" + (System.currentTimeMillis() - startTimeTwo));
    }
    运行结果如下所示,keySet()比entrySet()慢很多。

    原因分析:采用keySet方式时, 注释掉keySetMap.get(key)后性能一致。如下图所示,也就是说通过keySet方式获取value时又重新遍历Map集合,损耗了性能。因此不建议采用keySet方式获取value。





  • 相关阅读:
    html5阴影
    html5绘制字符串
    HTML5绘制几何图形
    Animation同时改变多个属性的动画
    Animation鱼眼效果
    Animation动画
    IE6中CSS常见BUG全集及解决方案——摘自网友
    transition多个属性同时渐变(width,height,background)
    【BZOJ2049】 [Sdoi2008]Cave 洞穴勘测
    【CF995F】 Cowmpany Cowmpensation
  • 原文地址:https://www.cnblogs.com/linux007/p/5777975.html
Copyright © 2011-2022 走看看