阅读本文大概需要 5 分钟。
来自:juejin.cn/post/7295353579002396726
Part1 引言
使用迭代器(Iterator)。 使用 keySet()获取键的集合,然后通过增强的 for 循环遍历键。使用 entrySet()获取键值对的集合,然后通过增强的 for 循环遍历键值对。使用 Java 8+ 的 Lambda 表达式和流。

entrySet进行遍历,在Java8中推荐使用Map.forEach()。给出的理由是遍历次数 上的不同。keySet遍历,需要经过两次 遍历。 entrySet遍历,只需要一次 遍历。
其中keySet遍历了两次,一次是转为Iterator对象,另一次是从hashMap中取出key所对应的value。
Part2 keySet如何遍历了两次
public class Test {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
for (String key : map.keySet()) {
String value = map.get(key);
System.out.println(key + ":" + value);
}
}
}
k1:v1
k2:v2
k3:v3
map,keySet()所返回的Set集合中的key,然后去HashMap中拿取value的。
增强for循环,for-each
public class Test {
public Test() {
}
public static void main(String[] args) {
Map<String, String> map = new HashMap();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
Iterator var2 = map.keySet().iterator();
while(var2.hasNext()) {
String key = (String)var2.next();
String value = (String)map.get(key);
System.out.println(key + ":" + value);
}
}
}
map.keySet().iterator()获取到了我们所需要看见的Iterator对象。iterator()方法1 iterator()

2 HashMap.KeySet#iterator()


final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
KeyIterator对象,那么究竟是在哪里进行了遍历呢?我们接着往下看去。3 HashMap.KeyIterator

final class KeyIterator extends HashIterator
implements Iterator<K> {
public final K next() { return nextNode().key; }
}
继承了 HashIterator类。实现了 Iterator接口。一个 next()方法。
HashIterator类4 HashMap.HashIterator

abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}
do-while循环操作,目的是找到一个第一个不为空的entry。HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
KeyIterator是extendHashIterator对象的。这里涉及到了继承的相关概念,大家忘记的可以找相关的文章看看,或者我也可以写一篇~~dog。public class Father {
public Father(){
System.out.println("father");
}
}
public class Son extends Father{
public static void main(String[] args) {
Son son = new Son();
}
}
father这句话。Part3 总结
使用keySet遍历,其实内部是使用了对应的 iterator()方法。iterator()方法是创建了一个KeyIterator对象。KeyIterator对象extendHashIterator对象。HashIterator对象的构造方法中,会遍历找到第一个不为空的entry。
keySet->iterator()->KeyIterator->HashIterator
推荐阅读:
SpringBoot + Apache tika 轻松实现各种文档内容解析
互联网初中高级大厂面试题(9个G) 内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper......等技术栈!
⬇戳阅读原文领取! 朕已阅
« 上一篇为什么停车要车头朝外?今天终于明白了!
下一篇 »贾诩为什么是三国时期最聪明的人?

发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。