Create PriorityQueue in Java - How to add Elements to PriorityQueue

Published April 04, 2022

First, import the package java.util.PriorityQueue. Once this package has been imported, use the syntax below to create a PriorityQueue:

PriorityQueue<Integer> PriorityQueue = new PriorityQueue<>();

 

Priority queues are ordered by default from smallest to largest, but you can modify which elements are ordered using the comparator interface.

Methods in PriorityQueue

  • add() – An element is inserted into the queue using this method

  • offer()-In addition to inserting the specified element into the queue, this method returns false when the queue is full.

 

In this example, we created a PriorityQueue named PQ, using the add() method to add 8 and 6 and the offer() method to add 4. We inserted 8 and 6 before 4, but since it is the smallest element, 4 will be returned as the head of the queue.

import java.util.PriorityQueue;

public class PriorityQueueExample {

    public static void main (String[] args) {

    // Create a PriorityQueue

        PriorityQueue<Integer> PQ = new PriorityQueue<>();

        // add() methods

        PQ.add(8);

        PQ.add(6);

        System.out.println("PriorityQueue: " + PQ);

        PQ.offer(4);

        System.out.println("Sorted PriorityQueue: " + PQ);

    }

}

 

 

Output:

PriorityQueue: [6, 8]

Sorted PriorityQueue: [4, 6, 8]

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

121 Views