Java PriorityQueue : Class



Java PriorityQueue :

  1. PriorityQueue class is an unbounded priority queue.
  2. PriorityQueue class is based on a priority heap.
  3. PriorityQueue elements are ordered according to their natural ordering or by using the Comparator provided at queue construction time, depending on which constructor is used.
  4. PriorityQueue does not permit null elements.
  5. PriorityQueue does not permit insertion of non-comparable objects.
  6. PriorityQueue class is using queue as data structure but it does not orders the elements in FIFO manner.

Class declaration :

public class PriorityQueue
   extends AbstractQueue
      implements Serializable

Parameters :

E -- This is the type of elements held in this collection.

Lets create an PriorityQueue using following line of code –

Example #1 : Create PriorityQueue

package com.c4learn.collection;

import java.util.Iterator;
import java.util.PriorityQueue;

public class PriorityQueueExample {
  public static void main(String[] args) {

    PriorityQueue<String> priQ = new PriorityQueue<String>();
    priQ.add("A");
    priQ.add("D");
    priQ.add("R");
    priQ.add("J");
    priQ.add("T");

    System.out.println("Iterating the Queue :");
    Iterator<String> itr = priQ.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }

    priQ.remove();
    priQ.remove();
  
    System.out.println("After removal : ");
    itr = priQ.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
  }
}

Output :

Iterating the Queue :
A
D
R
J
T
After removal : 
J
T
R