zoukankan      html  css  js  c++  java
  • 3.10 java基础总结集合①迭代器iterator

    迭代器iterator

    使用方法:
    * 1、Set/List.iterator (collection类的都有的工具方法)Map不是这个家族的,所以要转换成这个家族的才行
    * 2、hasNext()
    * 3、next()
    * List/Set可以不用迭代器,因为本身有for each
    *
    *
    * Map用的迭代器的效率更高,用foreach取键值出来的方法效率低,自己做小数据量的时候可以,业务中一般Map都用迭代器

    //Map的迭代器
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("a", 1);
    map.put("b", 2);
    map.put("c", 3);
    map.put("d", 4);
    map.put("e", 5);
    map.put("f", 6);


    //Entry,都可以,用以表示Entry是Map的内部接口,所以用.
    //使用entrySet讲map的键值对映射关系转换成Set集合


    Set<Map.Entry<String, Integer>> set= map.entrySet();

    //调用Set的iterator方法,得到迭代器
    Iterator<Map.Entry<String, Integer>> mapIter = set.iterator();


    //大数据的时候效率高,做业务一般用这个
    while(mapIter.hasNext()){
    //next得到的是Entry对象,而不是直接的键和值
    Map.Entry<String, Integer> entry = mapIter.next();
    String key = entry.getKey();
    Integer val = entry.getValue();
    System.out.println("key:" + key + " value:" + val);
    }

    //这种效率低,小数据操作的时候可以
    for(String key: map.keySet()){
    System.out.println(map.get(key));
    }

    Collection con = map.values();
    for(Object o : con){

    }


  • 相关阅读:
    [Bzoj2120]数颜色
    [Bzoj2049][Sdoi2008]Cave 洞穴勘测
    [2019上海网络赛F题]Rhyme scheme
    [2019上海网络赛J题]Stone game
    Codeforces Round #688 (Div. 2) C
    Educational Codeforces Round 99 (Rated for Div. 2) D
    Educational Codeforces Round 99 (Rated for Div. 2) B
    Codeforces Round #685 (Div. 2) D
    Codeforces Round #685 (Div. 2) C
    Codeforces Round #685 (Div. 2) B
  • 原文地址:https://www.cnblogs.com/chenyuanqiu2008/p/5274232.html
Copyright © 2011-2022 走看看