Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
Java.util.PriorityQueue class in Java
Next article icon

Java.util.PriorityQueue class in Java

Last Updated : 06 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report
It is a priority queue based on priority heap.
  • Elements in this class are in natural order or depends on the Constructor we used at this the time of construction.
  • It doesn't permit null pointers.
  • It doesn't allow inserting a non-comparable object, if it relies on natural ordering.
Constructors:
  • PriorityQueue(): Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
  • PriorityQueue(Collection extends E> c): Creates a PriorityQueue containing the elements in the specified collection.
  • PriorityQueue(int initialCapacity): Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.
  • PriorityQueue(int initialCapacity, Comparator super E> comparator): Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
  • PriorityQueue(PriorityQueue extends E> c): Creates a PriorityQueue containing the elements in the specified priority queue.
  • PriorityQueue(SortedSet extends E> c): Creates a PriorityQueue containing the elements in the specified sorted set.
Declaration :
  public class PriorityQueue     extends AbstractQueue     implements Serializable
Methods:
  1. add(element) : java.util.PriorityQueue.add() insert the elements to the Priority Queue. Syntax :
      public boolean add(E e)  Parameters  :  element : the element we need to add.  Return  :  call return true.  Exception :   -&gt ClassCastException   -&gt NullPointerException  
  2. comparator() : java.util.PriorityQueue.comparator() orders the elements in the queue. Syntax :
      public Comparator comparator()  Parameters  :  -------  Return  :  orders the queue or return null, if it is naturally ordered   Exception :   ----------  
  3. contains(Object obj) : java.util.PriorityQueue.contains(obj) returns true if the priority queue contains the element "obj". Syntax :
      public boolean contains(Object obj)  Parameters  :  obj : object to be checked  Return  :  true - if the object is present else, return false  Exception :     
  4. iterator() : java.util.PriorityQueue.iterator() iterates over the queue element. Syntax :
      public Iterator iterator()  Parameters  :  -------  Return  :  calls iterator over the elements in the queue.  Exception :   --------  
  5. offer(element) : java.util.PriorityQueue.offer() is required to insert a specific element to the given priority queue. Syntax :
      public boolean offer(E element)  Parameters  :  element : specific element to  be entered.  Return  :  call return true.  Exception :   -&gt ClassCastException   -&gt NullPointerException  
  6. peek() : java.util.PriorityQueue.peek() identifies the head element of the queue. Syntax :
      public E peek()      Parameters  :  -------  Return  :  calls if head exists, else null  Exception :   ------  
  7. poll() : java.util.PriorityQueue.poll() identifies the head and then removes it. Syntax :
      public E poll()      Parameters  :  ---  Return  :  calls if head exists, else null  Exception :   ------  
  8. remove(Object obj) : java.util.PriorityQueue.remove() removes a specific object from the queue. Syntax :
      public boolean remove(Object obj)  Parameters  :  obj : object to be removed  Return  :  true - if obj is removed  Exception :   ------  
  9. size() : java.util.PriorityQueue.size() returns the size of elements in the Priority Queue. Syntax :
      public int size()  Parameters  :  ----  Return  :  no. of elements  Exception :   ---------  
  10. toArray() : java.util.PriorityQueue.toArray() returns an array containing the elements of PriorityQueue. Syntax :
      public Object[] toArray()  Parameters  :  ------  Return  :  returns an array containing all the elements of PriorityQueue.  Exception :   --------  
  11. toArray(T[] array) : java.util.PriorityQueue.toArray(T[] a) returns the array having the elements of the Priority Queue. Syntax :
      public  T[] toArray(T[] array)  Parameters  :  array  : the array to which are to be sorted.   Return  :  call an array containing all the elements of the array.   Exception :   -> ArrayStoreException  -> NullPointerException  
  12. clear() : java.util.PriorityQueue.clear() clears all the elements of the PriorityQueue. Syntax :
      public void clear()          Parameters  :  ---  Return  :  ------  Exception :   ------  
  13. Java
    // Java Program illustrating the methods // of java.utl.priorityQueue class  // add(), comparator(), conatins(), iterator(), offer() // peek(), poll(), toArray(), size(), toArray(t[] g1), // remove(), clear()  import java.util.*; public class NewClass {     public static void main(String[] args)     {         // Creating a Priority Queue :         PriorityQueue <Integer> geek = new PriorityQueue <Integer> ();          for(int i=2; i<=20; i=i+2)         {             // Use of add() :             geek.add(new Integer (i));         }          System.out.println("geek PriorityQueue : " + geek);          // Use of comparator()          // No ordering is required here as it is naturally ordered.         Comparator geek_comp = geek.comparator();         System.out.println("geek PriorityQueue : " + geek_comp);          // Use of contains()          boolean check = geek.contains(6);         System.out.println("Use of contains() : " + check);          // Use of iterator()          Iterator g_iterator = geek.iterator();          System.out.print("Iterator values : ");         while(g_iterator.hasNext())         {             System.out.print(g_iterator.next() + " ");         }         System.out.println("");          // Use of offer()          geek.offer(3050);         System.out.println("geek PriorityQueue : " + geek);          // Use of peek()          System.out.println("Head of PriorityQueue via peek : " + geek.peek());          //Use of poll()          int h = geek.poll();         System.out.println("\nHead of PriorityQueue via poll : " + h);         System.out.println("geek PriorityQueue bcz of poll() : " + geek);          // Use of remove()         boolean r = geek.remove(8);         System.out.println("\nCan remove : " + r);         System.out.println("geek PriorityQueue bcz of remove() : " + geek);          // use of size()          System.out.println("\nSize of PriorityQueue : " + geek.size());          // Use of toArray()          Object[] g = geek.toArray();         System.out.print ( "Array from PriorityQueue : ");          for ( int i = 0; i<g.length; i++ )         {             System.out.print (g[i].toString() + " ") ;         }          System.out.println("\n");          // Use of toArray(t[] g1) :         Integer[] g2 = new Integer[5];         Integer[] g1 = geek.toArray(g2);         System.out.print ( "Array from PriorityQueue of size 5 : ");          for ( int i = 0; i<g1.length; i++ )         {             System.out.print (g1[i].toString() + " ") ;         }          System.out.println("\n");          // Use of clear()          geek.clear();         System.out.println("PriorityQueue after clear() : " + geek);      } } 
    Output :
      geek PriorityQueue : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]  geek PriorityQueue : null  Use of contains() : true  Iterator values : 2 4 6 8 10 12 14 16 18 20   geek PriorityQueue : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3050]  Head of PriorityQueue via peek : 2    Head of PriorityQueue via poll : 2  geek PriorityQueue bcz of poll() : [4, 8, 6, 16, 10, 12, 14, 3050, 18, 20]    Can remove : true  geek PriorityQueue bcz of remove() : [4, 10, 6, 16, 20, 12, 14, 3050, 18]    Size of PriorityQueue : 9  Array from PriorityQueue : 4 10 6 16 20 12 14 3050 18     Array from PriorityQueue of size 5 : 4 10 6 16 20 12 14 3050 18     PriorityQueue after clear() : []

Next Article
Java.util.PriorityQueue class in Java

M

Mohit Gupta_OMG
Improve
Article Tags :
  • Java
  • DSA
  • Java-Collections
  • Java - util package
  • Java-Functions
  • priority-queue
  • java-priority-queue
Practice Tags :
  • Java
  • Java-Collections
  • priority-queue

Similar Reads

    PriorityBlockingQueue Class in Java
    The PriorityBlockingQueue class is part of the java.util.concurrent package and implements a thread-safe, priority-based blocking queue. It is similar to the PriorityQueue, but it supports operations for blocking threads, such as take() and put() which are not available in PriorityQueue.Thread-safe
    9 min read
    PriorityQueue clear() Method in Java
    The Java.util.PriorityQueue.clear() method is used to remove all the elements from a PriorityQueue. Using the clear() method only clears all the element from the queue and does not delete the queue. In other words, we can say that the clear() method is used to only empty an existing PriorityQueue. S
    2 min read
    PriorityQueue in Java
    The PriorityQueue class in Java is part of the java.util package. It implements a priority heap-based queue that processes elements based on their priority rather than the FIFO (First-In-First-Out) concept of a Queue.Key Points:The PriorityQueue is based on the Priority Heap. The elements of the pri
    9 min read
    PriorityQueue add() Method in Java
    The Java.util.PriorityQueue.add() method in Java is used to add a specific element into a PriorityQueue. This method internally just calls the Java.util.PriorityQueue.offer() method with the value passed to it. So, it exactly works like offer() method. Syntax: Priority_Queue.add(Object element) Para
    2 min read
    PriorityQueue contains() Method in Java
    The Java.util.PriorityQueue.contains() method is used to check whether a specific element is present in the PriorityQueue or not. So basically it is used to check if a Queue contains any particular element or not. Syntax: Priority_Queue.contains(Object element) Parameters: The parameter element is o
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences