我是靠谱客的博主 苗条大碗,最近开发中收集的这篇文章主要介绍Iterator迭代器 遍历MapIterator迭代器 简单说明,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Iterator迭代器 简单说明

Iterator就是一个迭代器,主要用于遍历没有索引的类集 比如 Map


迭代器接口


Interface Iterator<E>
    boolean  hasNext() 
//Returns true if the iteration has more elements.
//遍历过程中,判定是否还有下一个元素。(从Collection对象的第一个元素开始)

     E  next() 
//Returns the next element in the iteration.
// 取出下一个元素

    void  remove() 
//Remove from the underlying collection the last element returned by the iterator (optional operation).
//移除刚刚遍历的元素

Example: 迭代器遍历HashMap

    long start = System.currentTimeMillis(); 
    Map<String,String> map = new HashMap<>();
    for(long i = 9999999 ; i > 0  ; i--){
        map.put(""+i, "");
    }
    System.out.println("Time PUT DATA IN MAP " + (System.currentTimeMillis()-start));

    List<Map<String,String>> ListMap = new ArrayList<>();

    start = System.currentTimeMillis();
    Iterator<Entry<String,String>> a = map.entrySet().iterator();


            while(a.hasNext()){
                a.next();
            }

            System.out.println("Time EntrySet " + (System.currentTimeMillis()-start));

            start = System.currentTimeMillis();
    Iterator<String> b = map.keySet().iterator();


            while(b.hasNext()){
                b.next();
            }
            System.out.println("Time KeySet" + (System.currentTimeMillis()-start));

输出结果

Time PUT DATA IN MAP 14405
Time EntrySet 217
Time KeySet233
因此 使用EntrySet 和 KeySet对性能造成的影响不大 可以各取所需;
但是网上的都比较倾向于使用EntrySet 作为新手表示不太懂 上面的结论欢迎批驳

最后

以上就是苗条大碗为你收集整理的Iterator迭代器 遍历MapIterator迭代器 简单说明的全部内容,希望文章能够帮你解决Iterator迭代器 遍历MapIterator迭代器 简单说明所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部