Stream Vs. Iterator in entrySet of a Map - Java 8

后端 未结 3 1894
轻奢々
轻奢々 2021-02-18 17:10

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-18 17:51

    The thing is:

    Map.Entry entry1 = set.iterator().next();
    Map.Entry entry2 = set.stream().findFirst().get();
    

    You are not comparing the values you put into the map. But Entry objects!

    In other words: it looks like your code is creating new Entry objects using your code. It is completely up to the internal implementation of that unmodifiable Map/Set what to return when it is asked for an iterator or a stream ... and as Eran was a bit quicker to lookup: the reason is that new Entry objects are created when iterating.

    So, when using equals() instead of == ... you get the expected output.

提交回复
热议问题