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

后端 未结 3 1833
轻奢々
轻奢々 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 18:01

    No both entry1 and entry2 are has same value but they are not pointing the same object because the each time you get the Map.Entry object it create new one.
    Look at the below code :

    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class Test1 {
    
        public static void main(String[] args) {
            final HashMap map = new HashMap<>();
            map.put("A", "B");
            final Set> set = Collections.unmodifiableMap(map).entrySet();
            Map.Entry entry1 = set.iterator().next();
            Map.Entry entry2 = set.stream().findFirst().get();
            System.out.println("entry1 : " + System.identityHashCode(entry1));
            System.out.println("entry2 : " + System.identityHashCode(entry2));
            for (int i = 0; i < 5; i++) {
                System.out.println("directly for set " + i + " : " + System.identityHashCode(set.stream().findFirst().get()));
            }
        }
    }
    

    The output is :

    entry1 : 1283928880
    entry2 : 295530567
    directly for set 0 : 2003749087
    directly for set 1 : 1324119927
    directly for set 2 : 990368553
    directly for set 3 : 1096979270
    directly for set 4 : 1078694789
    

    System.identityHashCode() will give hash code.

提交回复
热议问题