Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

priorityqueue
queue
java
priority

How to use PriorityQueue in Java

Educative Answers Team

The PriorityQueue class implements the Queue interface in Java. A PriorityQueue is beneficial when the objects are supposed to be processed based on the priority rather than the First-In-First-Out (FIFO) algorithm, which is usually implemented in the Queue interface. The internal working of the PriorityQueue is based on the Binary Heap.

The elements of the priority queue are ordered according to the natural ordering, or by a comparator provided at construction time of the queue, depending on which constructor is used.

Below is the visualization of implementing a PriorityQueue. The lowest number has the highest priority.

1 of 5

Example

The methods used are the ones from the Java Queue interface. Below is a sample code for implementing a PriorityQueue in Java:

import java.util.*; 
class MyClass {
  public static void main( String args[] ) {

    PriorityQueue<Integer> intQ = new PriorityQueue<>();
    // offer() and add() are used to add elements

    intQ.add(51);
    intQ.offer(6);
    intQ.add(72);
    intQ.add(1);
    intQ.add(2);
    intQ.offer(3);
    intQ.offer(4);
    intQ.add(11);
    intQ.add(19);

    System.out.println("Elements in this queue are: ");
    System.out.println(intQ);

    // printing size of the queue
    System.out.println("Size of this queue is: " + intQ.size());

    // removing values based on priority and printing them
    System.out.println("Priority Queue:");
    while(!intQ.isEmpty()){
      System.out.println(intQ.remove());
    }
  }
}

Printing out the PriorityQueue using the System.out.println command will not print the queue the order in which they were added. They will be printed in the order in which they are stored in the system. But when the remove() method is used to remove an object from the PriorityQueue, the object is removed on priority basis.

RELATED TAGS

priorityqueue
queue
java
priority
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring