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)?
9-5=4
is the priority of9
, andpq.peek()
returns the value, not the prioritynew 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 than5-9=-4
So the value
9
will be the first one.