PriorityQueue<Integer> with lambda expression

2.8k views Asked by At

Im trying to understand how lambda functions work with heaps in Java. the function below is to create a max heap

PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);

Can someone tell me what (x, y) -> y - x) does? Im told that "The lambda function will take two Integers as input parameters, subtract them from each other, and return the arithmetic result."

so if I do

PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
pq.add(9);

pq.add(5);

System.out.println(pq.peek());

Output is 9 since its a max heap but should I not get 4 as an output since (9-5=4)?

2

There are 2 answers

0
DelfikPro On

9-5=4 is the priority of 9, and pq.peek() returns the value, not the priority

new PriorityQueue<>(comparator); uses (x, y) -> y - x to compare and determine which value should be next to be peeked.

So 9-5=4 is greater than 5-9=-4

So the value 9 will be the first one.

0
Giorgi Tsiklauri On

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.