Java Priority Queue Methods Example

In this source code example, we will show you the usage of important Java Priority Queue class methods with examples.

PriorityQueue is a Queue data structure implementation in which objects are processed based on their priority. It's part of the Java Collections Framework and is present in the java.util package.

Priority Queue Important Methods

import java.util.PriorityQueue;

public class PriorityQueueMethods {
    public static void main(String[] args) {
        // Create a priority queue of integers
        PriorityQueue<Integer> numbers = new PriorityQueue<>();

        // 1. Add numbers to the priority queue
        numbers.add(15);
        numbers.add(10);
        numbers.add(25);
        numbers.add(5);

        // 2. Peek (retrieve but not remove) the head of the queue
        System.out.println("Peek: " + numbers.peek());

        // 3. Poll (retrieve and remove) the head of the queue
        System.out.println("Poll: " + numbers.poll());

        // 4. Check if the queue contains a specific number
        System.out.println("Contains 15? " + numbers.contains(15));

        // 5. Remove a specific number
        numbers.remove(15);
        System.out.println("Contains 15 after removal? " + numbers.contains(15));

        // 6. Get the size of the queue
        System.out.println("Size: " + numbers.size());

        // 7. Clear the priority queue
        numbers.clear();
        System.out.println("Size after clear: " + numbers.size());
    }
}

Output:

Peek: 5
Poll: 5
Contains 15? true
Contains 15 after removal? false
Size: 2
Size after clear: 0

Explanation:

1. A PriorityQueue of integers is created and populated.

2. The peek method retrieves the head of the queue (smallest integer) without removing it.

3. The poll method retrieves and removes the head of the queue.

4. The contains method checks if the queue contains a specific number.

5. The remove method removes a specific number from the queue.

6. The size method returns the number of elements in the queue.

7. The clear method removes all elements from the queue.


Comments