Search code examples
javaalgorithmdata-structurespriority-queue

How comparator and PriorityQueue in Java works?


This is the code i used to reverse the normal working of priorityQueue in Java. But i don't understand what is done by the lambda function i have put inside the parantheses. Can somedy explain that.

PriorityQueue pq = new PriorityQueue<>((a,b) -> b - a);

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b - a);
        
        pq.add(2);
        pq.add(4);
        pq.add(1);
        pq.add(100);
        
        System.out.println(pq);
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        
    }
} 

Solution

  • The comparison function is a function that must return any value less than 0 when the first parameter should be ordered before the second, any value greater than 0 when the second parameter should be ordered before the first and 0 if the two are equivalent for ordering.

    It is used in within the PriorityQueue internally to determine relative ordering of elements by comparing its result with 0.