Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the PriorityQueue.size() method in Java?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will learn how to use the PriorityQueue.size() method in Java.

Introduction

The PriorityQueue.size() method obtains the number of elements present in the PriorityQueue.

The PriorityQueue.size() method is present in the PriorityQueue class inside the java.util package.

Syntax

The syntax of the PriorityQueue.size() function is given below:

public int size();

Parameters

The PriorityQueue.size() method does not accept any parameters.

Return value

The PriorityQueue.size() method returns an integer value that denotes the number of elements in the PriorityQueue.

Code

Let us have a look at the code below.

import java.util.*;
class Main
{
public static void main(String[] args)
{
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
System.out.println("Number of elements in the priority queue are: " + pq.size());
pq.add(2);
pq.add(28);
pq.add(6);
pq.add(80);
pq.add(28);
pq.add(7);
pq.add(15);
System.out.println("Number of elements in the priority queue are: "+pq.size());
}
}
Using the PriorityQueue.size() method in Java

Explanation

  • In line 1, we import the required package.

  • In line 2, we make a Main class.

  • In line 4, we make a main() function.

  • In line 6, we declare a PriorityQueue that consists of Integer type elements.

  • In line 8, we print the current number of elements in the priority queue. Here, the output comes to 00.

  • From lines 10 to 16, we use the PriorityQueue.add() method to insert the elements in the PriorityQueue.

  • In line 18, we use the PriorityQueue.size() method to display the number of elements present in the PriorityQueue.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring