Wednesday, July 1, 2026
HomeLanguagesJavaPriorityQueue size() Method in Java

PriorityQueue size() Method in Java

The Java.util.PriorityQueue.size() method is used to get the size of the PriorityQueue or the number of elements present in the PriorityQueue.

Syntax:

Priority_Queue.size()

Parameters: This method does not takes any parameter.

Return Value: The method returns the size or the number of elements present in the PriorityQueue.

Below programs illustrate the Java.util.PriorityQueue.size() method:
Program 1:




// Java code to illustrate size()
import java.util.*;
  
public class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue<String> queue = new PriorityQueue<String>();
  
        // Use add() method to add elements into the Queue
        queue.add("Welcome");
        queue.add("To");
        queue.add("Geeks");
        queue.add("For");
        queue.add("Geeks");
  
        // Displaying the PriorityQueue
        System.out.println("PriorityQueue: " + queue);
  
        // Displaying the size of the PriorityQueue
        System.out.println("The size of the queue is: " + queue.size());
    }
}


Output:

PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The size of the queue is: 5

Program 2:




// Java code to illustrate size()
import java.util.*;
  
public class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
  
        // Use add() method to add elements into the Queue
        queue.add(10);
        queue.add(15);
        queue.add(30);
        queue.add(20);
        queue.add(5);
        queue.add(18);
  
        // Displaying the PriorityQueue
        System.out.println("PriorityQueue: " + queue);
  
        // Displaying the size of the PriorityQueue
        System.out.println("The size of the queue is: " + queue.size());
    }
}


Output:

PriorityQueue: [5, 10, 18, 20, 15, 30]
The size of the queue is: 6
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32517 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6900 POSTS0 COMMENTS
Nicole Veronica
12014 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6966 POSTS0 COMMENTS