Java PriorityQueue

Introduction

The PriorityQueue class in Java, part of the java.util package, is a queue that allows elements to be processed based on their priority. 

It is a priority heap-based data structure that orders elements according to their natural ordering or by a specified comparator. Elements of the PriorityQueue are ordered in a way that the least element is dequeued first.

Table of Contents

  1. What is the PriorityQueue Class?
  2. Common Methods
  3. Examples of Using the PriorityQueue Class
  4. Conclusion

1. What is the PriorityQueue Class?

The PriorityQueue class implements a priority queue, which processes elements based on their priority. It uses a heap data structure to maintain the elements in a specific order, ensuring efficient access to the smallest element. The elements can be ordered either according to their natural ordering (if they implement Comparable) or by a Comparator provided at the time of the queue's creation.

2. Common Methods

  • add(E e): Inserts the specified element into the priority queue.
  • offer(E e): Inserts the specified element into the priority queue (similar to add).
  • poll(): Retrieves and removes the head of this queue, or returns null if this queue is empty.
  • remove(): Retrieves and removes the head of this queue.
  • peek(): Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
  • element(): Retrieves, but does not remove, the head of this queue.
  • size(): Returns the number of elements in this collection.
  • clear(): Removes all of the elements from this priority queue.
  • contains(Object o): Returns true if this queue contains the specified element.
  • toArray(): Returns an array containing all of the elements in this queue.

3. Examples of Using the PriorityQueue Class

Example 1: Basic Usage of PriorityQueue

This example demonstrates how to create and use a PriorityQueue with default natural ordering.

import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(5);
        pq.add(1);
        pq.add(3);
        pq.add(10);

        System.out.println("PriorityQueue: " + pq);

        while (!pq.isEmpty()) {
            System.out.println("Poll: " + pq.poll());
        }
    }
}

Output:

PriorityQueue: [1, 5, 3, 10]
Poll: 1
Poll: 3
Poll: 5
Poll: 10

Example 2: Using a Comparator

This example shows how to create a PriorityQueue with a custom comparator to order elements in descending order.

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

public class PriorityQueueComparatorExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
        pq.add(5);
        pq.add(1);
        pq.add(3);
        pq.add(10);

        System.out.println("PriorityQueue: " + pq);

        while (!pq.isEmpty()) {
            System.out.println("Poll: " + pq.poll());
        }
    }
}

Output:

PriorityQueue: [10, 5, 3, 1]
Poll: 10
Poll: 5
Poll: 3
Poll: 1

Example 3: Peeking at the Head Element

This example demonstrates how to use the peek method to retrieve, but not remove, the head element of the PriorityQueue.

import java.util.PriorityQueue;

public class PriorityQueuePeekExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(5);
        pq.add(1);
        pq.add(3);
        pq.add(10);

        System.out.println("PriorityQueue: " + pq);
        System.out.println("Peek: " + pq.peek());

        while (!pq.isEmpty()) {
            System.out.println("Poll: " + pq.poll());
        }
    }
}

Output:

PriorityQueue: [1, 5, 3, 10]
Peek: 1
Poll: 1
Poll: 3
Poll: 5
Poll: 10

Example 4: Removing Elements

This example shows how to use the remove method to remove a specific element from the PriorityQueue.

import java.util.PriorityQueue;

public class PriorityQueueRemoveExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(5);
        pq.add(1);
        pq.add(3);
        pq.add(10);

        System.out.println("PriorityQueue: " + pq);

        pq.remove(3);
        System.out.println("After removing 3: " + pq);

        while (!pq.isEmpty()) {
            System.out.println("Poll: " + pq.poll());
        }
    }
}

Output:

PriorityQueue: [1, 5, 3, 10]
After removing 3: [1, 5, 10]
Poll: 1
Poll: 5
Poll: 10

Example 5: Checking for Element Containment

This example demonstrates how to check if a PriorityQueue contains a specific element.

import java.util.PriorityQueue;

public class PriorityQueueContainsExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(5);
        pq.add(1);
        pq.add(3);
        pq.add(10);

        System.out.println("PriorityQueue: " + pq);
        System.out.println("Contains 3: " + pq.contains(3));
        System.out.println("Contains 7: " + pq.contains(7));

        while (!pq.isEmpty()) {
            System.out.println("Poll: " + pq.poll());
        }
    }
}

Output:

PriorityQueue: [1, 5, 3, 10]
Contains 3: true
Contains 7: false
Poll: 1
Poll: 3
Poll: 5
Poll: 10

4. Conclusion

The PriorityQueue class in Java provides a way to handle elements based on their priority using a heap-based data structure. By using the methods provided by PriorityQueue, developers can efficiently manage and process elements according to their priority. The examples provided demonstrate common usage patterns and highlight the capabilities of the PriorityQueue class.

Comments