Java PriorityQueue Guide: Implementation & Examples

In Java, a priority queue is a special type of queue that orders elements based on their priority. In Java, a priority queue is implemented using the PriorityQueue class.

Here is an example code using a priority queue:

import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {
        // 创建一个优先级队列
        PriorityQueue<Integer> pq = new PriorityQueue<>();

        // 向队列中添加元素
        pq.add(5);
        pq.add(3);
        pq.add(8);
        pq.add(1);

        // 打印队列中的元素
        System.out.println("Priority Queue: " + pq);

        // 从队列中获取并移除最小的元素
        int minElement = pq.poll();
        System.out.println("Min Element: " + minElement);

        // 打印更新后的队列
        System.out.println("Updated Priority Queue: " + pq);
    }
}

In the example above, we created a priority queue called pq and added several elements to it. By calling the poll() method, we can retrieve and remove the smallest element from the queue. Lastly, we printed the updated queue.

With a priority queue, we can easily handle scenarios that require processing elements based on their priority, such as task scheduling and event handling.

bannerAds