I'm trying to understand how lambda functions work with heaps in Java.
Lambda Expression has nothing to do with Heap Data Structure, per se.
Lambda Expression - is a language feature, acting like an anonymous function, which you can use/pass as a value;
Heap - is a Data Structure, originally defined in Mathematics, and nowadays heavily used in the Computer Science domains.
Can someone tell me what (x, y) -> y - x) does?
That is your comparator, to wit, a lambda expression which implements a Comparator<T>
, and which you pass as an argument into your priority queue constructor.
PriorityQueue<T>
then makes use of that comparator, and utilizes int compare(T o1, T o2)
method, each time you fetch (poll/peek) an element from it.
PriorityQueue<T>
relies on a contract, that:
int compare(T o1, T o2) Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
So, in your code:
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
pq.add(9);
pq.add(5);
System.out.println(pq.peek());
Two numbers are enqueued in the Heap/PQ, and when you .peek()
, 9
and 5
are passed into x
and y
respectively. As 9-5>0
true is returned.
Output is 9 since its a max heap but should I not get 4 as an output since (9-5=4)?
9-5=4
is only relevant for the comparator, to decide whether the comparison of two elements end up in 0, positive, or negative number, as already explained above.