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.
source
share