Iterator迭代器 遍历Map

xiaoxiao2021-02-28  68

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

转载请注明原文地址: https://www.6miu.com/read-71730.html

最新回复(0)