流VS. Map的entrySet中的迭代器-Java 8 [英] Stream Vs. Iterator in entrySet of a Map - Java 8

查看:234
本文介绍了流VS. Map的entrySet中的迭代器-Java 8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,以下代码应打印true,因为StreamIterator都指向第一个元素.

To my understanding, the following code should have print true, since both Stream and Iterator are pointing to the first element.

但是,当我运行以下代码时,它正在打印false:

However, when I ran the following code it is printing false:

final HashMap<String, String> map = new HashMap<>();
map.put("A", "B");
final Set<Map.Entry<String, String>> set = Collections.unmodifiableMap(map).entrySet();
Map.Entry<String, String> entry1 = set.iterator().next();
Map.Entry<String, String> entry2 = set.stream().findFirst().get();
System.out.println(entry1 == entry2);

这种不同行为的原因可能是什么?

What could be the reason for this different behavior?

推荐答案

两个条目都引用了Map的相同逻辑条目(其键为"A",值为"B").但是,它们不是同一实例.

Both entries are referring to the same logical entry of your Map (whose key is "A" and value is "B"). However, they are not the same instance.

如果您对Collections.unmodifiableMap(map)的实现进行了足够深入的研究,您会发现遍历Collections.unmodifiableMap(map)返回的地图的entrySet会返回一个新的Map.Entry,该Map.Entry包裹了原始的可修改条目:

If you dig deep enough in the implementation of Collections.unmodifiableMap(map) you'll see that iterating over the entrySet of the map returned by Collections.unmodifiableMap(map) returns a new Map.Entry which wraps the original modifiable entry:

public Map.Entry<K,V> next() {
  return new UnmodifiableEntry<>(i.next());
}

我假设您在调用set.stream().findFirst().get()时也创建了一个新实例Map.Entry实例,因此这两种方法返回的实例不同.

I'm assuming a new instance Map.Entry instance is also created when you call set.stream().findFirst().get(), so the two methods return different instances.

即使您两次调用相同的方法,也会得到差异实例,即以下代码也会打印false:

Even if you'll call the same method twice you'll get difference instances, i.e. the following code will also print false:

Map.Entry<String, String> entry1 = set.iterator().next();
Map.Entry<String, String> entry2 = set.iterator().next();
System.out.println(entry1 == entry2);

另一方面,如果您直接从原始的HashMap获取条目,则将获得true:

On the other hand, if you obtain the entry directly from the original HashMap, you will get true:

Map.Entry<String, String> entry1 = map.entrySet ().iterator().next();
Map.Entry<String, String> entry2 = map.entrySet ().stream().findFirst().get();
System.out.println (entry1==entry2);

如果是这种情况,则该条目不会被新实例包装,因此entrySet ().iterator().next()entrySet ().stream().findFirst().get()都返回相同的实例.

If this case the entry is not wrapped by a new instance, so both entrySet ().iterator().next() and entrySet ().stream().findFirst().get() return the same instance.

这篇关于流VS. Map的entrySet中的迭代器-Java 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆