Priority Queue of Pair in Java with Examples
In Java, a priority queue of pairs can be implemented using the PriorityQueue
class and the Pair
class from the javafx.util
package. Here are two methods to implement a priority queue of pairs in Java:
Method 1: Using a Comparator
In this method, we create a Comparator
object that compares pairs based on their first element. We then create a PriorityQueue
object and pass the Comparator
object as a parameter to its constructor. We can then add pairs to the priority queue using the add()
method, and remove the pair with the highest priority using the poll()
method.
Example:
import javafx.util.Pair;
import java.util.Comparator;
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
// Create a Comparator object that compares pairs based on their first element
Comparator<Pair<Integer, String>> comparator = new Comparator<Pair<Integer, String>>() {
@Override
public int compare(Pair<Integer, String> p1, Pair<Integer, String> p2) {
return p1.getKey().compareTo(p2.getKey());
}
};
// Create a PriorityQueue object and pass the Comparator object as a parameter to its constructor
PriorityQueue<Pair<Integer, String>> pq = new PriorityQueue<>(comparator);
// Add pairs to the priority queue
pq.add(new Pair<>(3, "Alice"));
pq.add(new Pair<>(1, "Bob"));
pq.add(new Pair<>(2, "Charlie"));
// Remove the pair with the highest priority
Pair<Integer, String> highestPriorityPair = pq.poll();
System.out.println(highestPriorityPair.getValue()); // Output: "Bob"
}
}
Method 2: Using Comparable
In this method, we make the Pair
class implement the Comparable
interface and define the compareTo()
method to compare pairs based on their first element. We can then create a PriorityQueue
object and add pairs to it using the add()
method, and remove the pair with the highest priority using the poll()
method.
Example:
import javafx.util.Pair;
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
// Create a PriorityQueue object
PriorityQueue<Pair<Integer, String>> pq = new PriorityQueue<>();
// Add pairs to the priority queue
pq.add(new Pair<>(3, "Alice"));
pq.add(new Pair<>(1, "Bob"));
pq.add(new Pair<>(2, "Charlie"));
// Remove the pair with the highest priority
Pair<Integer, String> highestPriorityPair = pq.poll();
System.out.println(highestPriorityPair.getValue()); // Output: "Bob"
}
}
// Make the Pair class implement the Comparable interface
class Pair<K extends Comparable<? super K>, V> implements Comparable<Pair<K, V>> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
// Define the compareTo() method to compare pairs based on their first element
@Override
public int compareTo(Pair<K, V> other) {
return this.key.compareTo(other.key);
}
}