Java Priority Queue Custom Sorting Guide

To customize the sorting of a PriorityQueue, you need to implement the Comparator interface and override its compare() method. The Comparator interface allows you to define the logic for comparing elements. Then, you can pass your custom Comparator object as a parameter to the constructor of the PriorityQueue.

Here is an example demonstrating how to use PriorityQueue to customize sorting:

import java.util.Comparator;
import java.util.PriorityQueue;

public class PriorityQueueCustomSorting {
    public static void main(String[] args) {
        // 创建自定义的Comparator对象
        Comparator<Integer> customComparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer num1, Integer num2) {
                // 根据数字的绝对值进行比较
                return Integer.compare(Math.abs(num1), Math.abs(num2));
            }
        };

        // 创建PriorityQueue并传入自定义的Comparator对象
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(customComparator);

        // 添加元素到PriorityQueue
        priorityQueue.add(-10);
        priorityQueue.add(5);
        priorityQueue.add(-3);
        priorityQueue.add(8);

        // 输出PriorityQueue中的元素
        while (!priorityQueue.isEmpty()) {
            System.out.println(priorityQueue.poll());
        }
    }
}

In the example above, we created a custom Comparator object that compares numbers based on their absolute values. Then, we created a PriorityQueue and passed the custom Comparator object to its constructor. Finally, we added some elements to the PriorityQueue and used the poll() method to retrieve and output these elements in the custom sorting order.

Running the above code will produce the following output:

-3
5
-10
8

It can be seen that the elements in the PriorityQueue are arranged in a custom sorting order.

bannerAds