Trying to understand different () for threads in Java8

I was looking at a Java8 book where the flow was explicitly explained. It is mentioned that the equality for creating individual elements is determined by the implementation of the method hashCode()and equals(). So I wrote the code below to understand an example:

static class Order{
        public Order(int id,Double value){
            this.id = id;
            this.value = value;
        }
        int id;
        Double value;
        @Override
        public int hashCode() {
            System.out.println("In Hashcode() - " + this.id +","+this.value);
            return this.id;
        }
        @Override
        public boolean equals(Object o){
            System.out.println("In Equals()");
            return this.id == ((Order)o).id;
        }
    }

    public static void main(String[] args) {
        Stream<Order> orderList = Stream.of(new Order(1,10.0),new Order(2,140.5),new Order(2,100.8));
        Stream<Order> biggerOrders = orderList.filter(o->o.value > 75.0);
        biggerOrders.distinct().forEach(o->System.out.println("OrderId:"+ o.id));
    }

He made the following conclusion:

In Hashcode() - 2,140.5
In Hashcode() - 2,140.5
OrderId:2
In Hashcode() - 2,100.8
In Equals()

I am confused by why the hashCode method in the same Order object (2,140.5) is called twice before comparing it with another Order object (2,100.8).

Thanks in advance.

+4
source share
2 answers

hashCode, , () HashMap ( HashMap). , () hashmap, .

. hashCode.

+2

answerd by @Adi, distinct() HashMap, hashCode() Order.

,

java.util.stream.DistinctOps.makeRef()

return new Sink.ChainedReference<T, T>(sink) {
    Set<T> seen;

    @Override
    public void begin(long size) {
        seen = new HashSet<>();
        downstream.begin(-1);
    }

    @Override
    public void end() {
        seen = null;
        downstream.end();
    }

    @Override
    public void accept(T t) {
        if (!seen.contains(t)) {//first call is made here
            seen.add(t);//second call is made here
            downstream.accept(t);
        }
    }
};

stacktrace .

enter image description here enter image description here

+3

Source: https://habr.com/ru/post/1622494/


All Articles