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?
In the provided code,
aandbrepresent the elements present in the heap (PriorityQueue). The lambda expression(a, b) -> map.get(b) - map.get(a)is used as the comparator for thePriorityQueue, 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 themapassociated with elementsaandb.The lambda expression
(a, b) -> map.get(b) - map.get(a)subtracts the value associated with elementafrom the value associated with elementb. This means that the element with a higher value in themapwill be considered greater, and therefore, will have a higher priority in thePriorityQueue. Consequently, thePriorityQueuewill act as a max heap, where the element with the highest value in themapwill 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 themaphas the highest priority.