(Java) Priority Queue Lambda Expression

In your case the lambda expression is a custom Comparator that 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. Since you can customize it, you can even return a negative number when first argument is numerically greater than the second argument. Assume matrix[n1.row][n1.col] is greater than matrix[n2.row][n2.col], In your first code, the lambda expression will return a possitive number, in the second code, it will return a negative number oppositely.

In PriorityQueue, it always puts samller ones before greater ones, in other words, it stores elements in ascending order(for simplicity, assume it’s ordered internally). But the order is decided by your custom Comparator if you provide one, When you add nodes to PriorityQueue by heap.add(new Node(i, 0));, it finally goes to this method:

    private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            // this is where the custom comparator being used, x is the first argument, 
            // e is the second argument. When it return a positive integer or zero, 
            // x will be positioned after e since comparator says x is greater than e.            
            if (comparator.compare(x, (E) e) >= 0)
            queue[k] = e;
            k = parent;
        queue[k] = x;

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top