HOWTO · Java
Java 中的優先順序佇列比較器
本教程演示瞭如何在 Java 中使用 PriorityQueue 比較器方法。
本頁內容
在優先順序佇列中,每個元素都使用與其關聯的特定優先順序進行處理。該優先順序在與優先順序佇列關聯的比較器函式中定義。
預設情況下,優先順序佇列是自然排序的;比較器用於給優先順序佇列一個特定的順序。這演示了在優先順序佇列中使用比較器。
在 Java PriorityQueue 中建立自定義比較器
讓我們建立一個自定義比較器來按降序對 PriorityQueue 進行排序。
參見示例:
package delftstack;
import java.util.Comparator;
import java.util.PriorityQueue;
public class PQ_Comparator {
public static void main(String[] args) {
// Create a priority queue
PriorityQueue<Integer> Demo_PQ = new PriorityQueue<>(new Sort_Comparator());
Demo_PQ.add(3);
Demo_PQ.add(4);
Demo_PQ.add(6);
Demo_PQ.add(5);
Demo_PQ.add(1);
System.out.print("Sorted PriorityQueue According to the comparator: " + Demo_PQ);
}
}
// Comparator class
class Sort_Comparator implements Comparator<Integer> {
@Override
public int compare(Integer x, Integer y) {
if (x < y) {
return 1;
}
if (x > y) {
return -1;
}
return 0;
}
}
上面的程式碼在類 Sort_Comparator 中建立了一個自定義比較器,並在優先順序佇列中使用它以降序對其進行排序。
見輸出:
Sorted PriorityQueue According to the comparator: [6, 5, 4, 3, 1]
直接在 Java PriorityQueue 中建立比較器
我們也可以直接在優先順序佇列中建立一個比較器。讓我們按降序對同一任務的優先順序佇列進行排序。
參見示例:
package delftstack;
import java.util.*;
public class PQ_Comparator {
public static void main(String[] args) {
// Create a priority queue
PriorityQueue<Integer> Demo_PQ = new PriorityQueue<Integer>(Collections.reverseOrder());
// PriorityQueue<Integer> Demo_PQ = new PriorityQueue<Integer>((a,b) -> b - a);
// PriorityQueue<Integer> Demo_PQ = new PriorityQueue<Integer>((a,b) -> b.compareTo(a));
Demo_PQ.add(3);
Demo_PQ.add(4);
Demo_PQ.add(6);
Demo_PQ.add(5);
Demo_PQ.add(1);
System.out.print("Sorted PriorityQueue According to the comparator: " + Demo_PQ);
}
}
上面的程式碼使用內建函式 Collections.reverseOrder 對優先順序進行降序排序。註釋中給出的其他兩個比較器也執行相同的操作。
見輸出:
Sorted PriorityQueue According to the comparator: [6, 5, 4, 3, 1]