what are the inputs given to the lambda expression(a,b) while creating a max priority queue in java

54 Views Asked by At

Started learning dsa and came across priority queues but I am stuck at lambda expressions in priority queue in java.

Map<Integer, Integer> map = new HashMap<>();
PriorityQueue<Integer> q = new PriorityQueue<>((a,b)->map.get(b)-map.get(a));

In the above expressions, how will this heap be a max heap, how a,b values are to be considered whats their source? I have understood that the lambda expressions return -ve or +ve values and on that basis, it's decided whether its going to be a max or min heap but what are a,b how are they evaluated, from where they are received.

Are a,b the values from heap? If they are, which values are they, the top ones or the bottom ones considering a max heap?

1

There are 1 best solutions below

0
vs01 On

In the provided code, a and b represent the elements present in the heap (PriorityQueue). The lambda expression (a, b) -> map.get(b) - map.get(a) is used as the comparator for the PriorityQueue, which determines how elements are compared and ordered in the heap.

In a PriorityQueue, the elements are sorted based on the result of the comparator. The comparator is applied to the elements present in the queue to determine their relative order. In this case, the lambda expression compares the values of the keys in the map associated with elements a and b.

The lambda expression (a, b) -> map.get(b) - map.get(a) subtracts the value associated with element a from the value associated with element b. This means that the element with a higher value in the map will be considered greater, and therefore, will have a higher priority in the PriorityQueue. Consequently, the PriorityQueue will act as a max heap, where the element with the highest value in the map will be at the root (top) of the heap.

In other words, the lambda expression is used to define the priority or ordering of elements in the PriorityQueue, and by subtracting the values in reverse order (b - a), we create a max heap where the element with the highest value in the map has the highest priority.