Iterator迭代器 遍历Map

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 作为新手表示不太懂 上面的结论欢迎批驳

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值