To create a priority queue of pairs in Java, you can define a custom class that represents a pair and implements the Comparable
interface, and then use the PriorityQueue
class to create a priority queue of the pair objects.
Here is an example of how you can create a priority queue of pairs in Java:
import java.util.PriorityQueue; class Pair implements Comparable<Pair> { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int compareTo(Pair other) { // Compare the pairs based on the first element return this.first - other.first; } } PriorityQueue<Pair> queue = new PriorityQueue<>(); // Add some pairs to the queue queue.add(new Pair(1, 2)); queue.add(new Pair(3, 4)); queue.add(new Pair(2, 3)); // Print the pairs in the queue while (!queue.isEmpty()) { Pair pair = queue.poll(); System.out.println(pair.first + ", " + pair.second); }
In this example, a Pair
class is defined that represents a pair of integers. The Pair
class implements the Comparable
interface and overrides the compareTo
method to specify how the pairs should be compared. The PriorityQueue
class is then used to create a priority queue of Pair
objects, and some pairs are added to the queue using the add
method. The poll
method is then used to retrieve and remove the pairs from the queue, and the elements of the pairs are printed to the console.
Keep in mind that the PriorityQueue
class is a min-heap, meaning that the elements with the lowest priority (as determined by the compareTo
method) are at the top of the queue. If you want to create a max-heap, you can use the Collections.reverseOrder
method as the comparator for the PriorityQueue
. For example:
PriorityQueue<Pair> queue = new PriorityQueue<>(Collections.reverseOrder());
In this example, the PriorityQueue
is created with the Collections.reverseOrder
comparator, which specifies that the elements with the highest priority should be at the top of the queue.