我是靠谱客的博主 苗条大碗,这篇文章主要介绍Iterator迭代器 遍历MapIterator迭代器 简单说明,现在分享给大家,希望可以做个参考。

Iterator迭代器 简单说明

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


迭代器接口

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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迭代器内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部