Java: Remove all the elements from a priority queue
5. Clear PriorityQueue
Write a Java program to remove all elements from a priority queue.
Sample Solution:-
Java Code:
import java.util.*;
  public class Example5 {
  public static void main(String[] args) {
   // Create Priority Queue
           PriorityQueue<String> pq1 = new PriorityQueue<String>();  
   // use add() method to add values in the Priority Queue
          pq1.add("Red");
          pq1.add("Green");
          pq1.add("Black");
          pq1.add("White");
    System.out.println("Original Priority Queue: "+pq1);
   
   // Removing all the elements from the Priority Queue
    pq1.clear();
 
    System.out.println("The New Priority Queue: " + pq1);
  } 
}
Sample Output:
Original Priority Queue: [Black, Red, Green, White] The New Priority Queue: []
For more Practice: Solve these Related Problems:
- Write a Java program to clear a PriorityQueue using clear() and then verify the queue is empty by printing its size.
- Write a Java program to remove all elements from a PriorityQueue one by one using poll() and print each removed element.
- Write a Java program to iteratively remove elements from a PriorityQueue until it is empty, then print a confirmation message.
- Write a Java program to use a while loop to continuously remove and print elements from a PriorityQueue until no elements remain.
Go to:
PREV : Insert Element into PriorityQueue.
NEXT : Count PriorityQueue Elements.
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
