PriorityBlockingQueue Class in Java

06 Nov, 2020
The PriorityBlockingQueue is an unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. Since it is unbounded, adding elements may sometimes fail due to resource exhaustion resulting in OutOfMemoryError. This class does not permit null elements. PriorityBlockingQueue class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. 
The Iterator provided in method iterator() and the Spliterator provided in the method spliterator() are not guaranteed to traverse the elements of the PriorityBlockingQueue in any particular order. For ordered traversal, use Arrays.sort(pq.toArray()). Also, method drainTo() can be used to remove some or all elements in priority order and place them in another collection.
Operations on this class make no guarantees about the ordering of elements with equal priority. If an ordering is needed to be enforced, define custom classes or comparators that use a secondary key to break ties in primary priority values. This class is a member of the Java Collections Framework.
The Hierarchy of PriorityBlockingQueue 
It implements Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces and extends AbstractQueue<E> class.
Declaration: 
public class PriorityBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable
Here, E is the type of elements held in this collection.
In order to create an instance of PriorityBlockingQueue, we need to import it from java.util.concurrent.PriorityBlockingQueue.
1. PriorityBlockingQueue() – Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering. Adding element more than the initial capacity changes the capacity of the PriorityBlockingQueue dynamically as the PriorityBlockingQueue is not capacity constrained.
PriorityBlockingQueue<E> pbq = new PriorityBlockingQueue<E>();
Example: 
Java
// Java program to demonstrate// PriorityBlockingQueue() constructor  import java.util.concurrent.PriorityBlockingQueue;  public class GFG {      public static void main(String[] args)    {          // create object of PriorityBlockingQueue        // using PriorityBlockingQueue() constructor        PriorityBlockingQueue<Integer> pbq            = new PriorityBlockingQueue<Integer>();          // add  numbers        pbq.add(1);        pbq.add(2);        pbq.add(3);        pbq.add(4);        pbq.add(5);          // print queue        System.out.println("PriorityBlockingQueue:" + pbq);    }}
PriorityBlockingQueue:[1, 2, 3, 4, 5]
 
2. PriorityBlockingQueue(Collection<? extends E> c) – Creates a PriorityBlockingQueue containing the elements in the specified collection.
PriorityBlockingQueue<E> pbq = new PriorityBlockingQueue(Collection<? extends E> c);
Example: 
Java
// Java program to demonstrate// PriorityBlockingQueue(Collection c) constructor  import java.util.concurrent.PriorityBlockingQueue;import java.util.*;  public class GFG {      public static void main(String[] args)    {          // Creating a Collection        Vector<Integer> v = new Vector<Integer>();        v.addElement(1);        v.addElement(2);        v.addElement(3);        v.addElement(4);        v.addElement(5);          // create object of PriorityBlockingQueue        // using PriorityBlockingQueue(Collection c)        // constructor        PriorityBlockingQueue<Integer> pbq            = new PriorityBlockingQueue<Integer>(v);          // print queue        System.out.println("PriorityBlockingQueue:" + pbq);    }}
  
PriorityBlockingQueue:[1, 2, 3, 4, 5]
 
3. PriorityBlockingQueue(int initialCapacity) – Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural ordering. Example:
Java
// Java program to demonstrate// PriorityBlockingQueue(int initialCapacity)// constructor  import java.util.concurrent.PriorityBlockingQueue;  public class GFG {      public static void main(String[] args)    {        // define capacity of PriorityBlockingQueue        int capacity = 15;          // create object of PriorityBlockingQueue        // using PriorityBlockingQueue(int initialCapacity)        // constructor        PriorityBlockingQueue<Integer> pbq            = new PriorityBlockingQueue<Integer>(capacity);          // add  numbers        pbq.add(1);        pbq.add(2);        pbq.add(3);          // print queue        System.out.println("PriorityBlockingQueue:" + pbq);    }}
PriorityBlockingQueue:[1, 2, 3]
 
4. PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator) – Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator. Example: 
Java
// Java program to demonstrate// PriorityBlockingQueue(int initialCapacity, Comparator// comparator) constructor  import java.util.concurrent.PriorityBlockingQueue;import java.util.*;  public class GFG {      public static void main(String[] args)    {        // define capacity of PriorityBlockingQueue        int capacity = 15;          // create object of PriorityBlockingQueue        PriorityBlockingQueue<Integer> pbq            = new PriorityBlockingQueue<Integer>(                capacity, Comparator.reverseOrder());          // add  numbers        pbq.add(1);        pbq.add(2);        pbq.add(3);          // print queue        System.out.println("PriorityBlockingQueue:" + pbq);    }}
  
PriorityBlockingQueue:[3, 1, 2]
 
1. Adding Elements
The add(E e) method of PriorityBlockingQueue inserts the element passed as a parameter to the method at the tail of this PriorityBlockingQueue. This method returns true if the adding of the element is successful. Else it returns false. 
Java
// Java program to demonstrate adding elements// to the PriorityBlockingQueue  import java.util.concurrent.PriorityBlockingQueue;  public class AddingElementsExample {      public static void main(String[] args)    {        // define capacity of PriorityBlockingQueue        int capacity = 15;          // create object of PriorityBlockingQueue        PriorityBlockingQueue<Integer> pbq            = new PriorityBlockingQueue<Integer>(capacity);          // add  numbers        pbq.add(1);        pbq.add(2);        pbq.add(3);          // print queue        System.out.println("PriorityBlockingQueue:" + pbq);    }}
PriorityBlockingQueue:[1, 2, 3]
 
2. Removing Elements
The remove(Object o) method of PriorityBlockingQueue is used to delete an element from this queue. This method removes a single instance of the element passed as the parameter if it is present. It returns true if and only if the element was removed, else it returned false. clear() is used to remove all the elements at once.
Java
// Java program to demonstrate removing// elements from the PriorityBlockingQueue  import java.util.concurrent.PriorityBlockingQueue;  public class RemovingElementsExample {      public static void main(String[] args)    {        // define capacity of PriorityBlockingQueue        int capacity = 15;          // create object of PriorityBlockingQueue        PriorityBlockingQueue<Integer> pbq            = new PriorityBlockingQueue<Integer>(capacity);          // add  numbers        pbq.add(1);        pbq.add(2);        pbq.add(3);          // print queue        System.out.println("PriorityBlockingQueue:" + pbq);          // remove all the elements        pbq.clear();          // print queue        System.out.println("PriorityBlockingQueue:" + pbq);    }}
PriorityBlockingQueue:[1, 2, 3]
PriorityBlockingQueue:[]
 
3. Accessing Elements 
The peek() method of PriorityBlockingQueue returns the element at the head of the PriorityBlockingQueue. It retrieves the value of the head of LinkedBlockingQueue but does not remove it. If the PriorityBlockingQueue does not contain any element, then this method returns null. A PriorityBlockingQueue queue uses the same ordering rules as class PriorityQueue.
Java
// Java Program Demonstrate accessing// elements of PriorityBlockingQueue  import java.util.concurrent.PriorityBlockingQueue;  public class AccessingElementsExample {    public static void main(String[] args)    {        // define capacity of PriorityBlockingQueue        int capacityOfQueue = 5;          // create object of PriorityBlockingQueue        PriorityBlockingQueue<Integer> PrioQueue            = new PriorityBlockingQueue<Integer>(                capacityOfQueue);          // Add elements to PriorityBlockingQueue        PrioQueue.add(464161);        PrioQueue.add(416165);          // print PrioQueue        System.out.println("PrioQueue: " + PrioQueue);          // get head of PriorityBlockingQueue        int head = PrioQueue.peek();          // print head of PriorityBlockingQueue        System.out.println("Head of Queue: " + head);    }}
PrioQueue: [416165, 464161]
Head of Queue: 416165
4. Iterating
The iterator() method of PriorityBlockingQueue class Returns an iterator over the elements in this queue. The elements returned from this method do not follow any order. The returned iterator is weakly consistent.
Java
// Java Program Demonstrate iterating// over PriorityBlockingQueue  import java.util.concurrent.PriorityBlockingQueue;import java.util.*;  public class IteratingExample {    public static void main(String[] args)    {          // define capacity of PriorityBlockingQueue        int capacityOfQueue = 5;          // create object of PriorityBlockingQueue        PriorityBlockingQueue<String> names            = new PriorityBlockingQueue<String>(                capacityOfQueue);          // Add names of students of girls college        names.add("Geeks");        names.add("forGeeks");        names.add("A");        names.add("Computer");        names.add("Portal");          // Call iterator() method of PriorityBlockingQueue        Iterator iteratorVals = names.iterator();          // Print elements of iterator        // created from PriorityBlockingQueue        System.out.println("The Names are:");          while (iteratorVals.hasNext()) {            System.out.println(iteratorVals.next());        }    }}
The Names are:
A
Computer
Geeks
forGeeks
Portal

5. Comparator Example
The comparator() method of PriorityBlockingQueue returns the comparator that can be used to order the elements in a PriorityBlockingQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.
Java
// Java Program Demonstrate comparator()// method and passing Comparator to PriorityBlockingQueue  import java.util.concurrent.PriorityBlockingQueue;import java.util.*;  public class ComparatorExample {    public static void main(String[] args)        throws InterruptedException    {          // create object of PriorityBlockingQueue        PriorityBlockingQueue<Integer> PrioQueue            = new PriorityBlockingQueue<Integer>(                10, new Comparator<Integer>() {                    public int compare(Integer a, Integer b)                    {                        return a - b;                    }                });          // Add numbers to PriorityBlockingQueue        PrioQueue.put(45815616);        PrioQueue.put(4981561);        PrioQueue.put(4594591);        PrioQueue.put(9459156);          // get String representation of        // PriorityBlockingQueue        String str = PrioQueue.toString();          // Creating a comparator using comparator()        Comparator comp = PrioQueue.comparator();          // Displaying the comparator values        System.out.println("Comparator value: " + comp);          if (comp == null)            System.out.println(                "PriorityBlockingQueue follows natural ordering");        else            System.out.println(                "PriorityBlockingQueue follows : " + comp);    }}
Comparator value: ComparatorExample$1@27bc2616
PriorityBlockingQueue follows : ComparatorExample$1@27bc2616
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/PriorityBlockingQueue.html
Ganeshchowdharysadanala
Java - util package
Java-Collections
Java-PriorityBlockingQueue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java