w3resource

Java: Count the number of elements in a priority queue


6. Count PriorityQueue Elements

Write a Java program to count the number of elements in a priority queue.

Sample Solution:-

Java Code:

import java.util.PriorityQueue;
  public class Exercise6 {
  public static void main(String[] args) {
    // create an empty Priority Queue
    PriorityQueue<String> pq = new PriorityQueue<String>();  
   // use add() method to add values in the Priority Queue
          pq.add("Red");
          pq.add("Green");
          pq.add("Black");
          pq.add("Pink");
          pq.add("orange");
     System.out.println("Priority Queue: " + pq);
    System.out.println("Size of the Priority Queue: " + pq.size());
   }
}

Sample Output:

Priority Queue: [Black, Pink, Green, Red, orange]                      
Size of the Priority Queue: 5

For more Practice: Solve these Related Problems:

  • Write a Java program to determine the size of a PriorityQueue using the size() method and then print the count.
  • Write a Java program to iterate over a PriorityQueue and manually count the elements, then compare the result with size().
  • Write a Java program to convert a PriorityQueue to a stream and use count() to display the number of elements.
  • Write a Java program to add elements to a PriorityQueue, remove some, and then print the updated count using size().

Go to:


PREV : Clear PriorityQueue.
NEXT : Compare PriorityQueues.

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.



Follow us on Facebook and Twitter for latest update.