Java

PriorityQueue Interface – Java Collections

We saw how a Queue delivers requests based on FIFO in the last lesson (First in First out). What would happen if we preferred to serve requests based on priority than FIFO? This kind of approach would be favored in a real-world situation since it is more flexible and effective. This is possible thanks to PriorityQueue, which fulfills the request in accordance with the priority that we define using Comparator.

Java PriorityQueue Example

In this example, I’m adding a few Strings to the PriorityQueue and giving the constructor of the PriorityQueue the Comparator (called MyComparator) to work with.
I ordered the Strings in the MyComparator Java class according to their length, which implies that the String length is the priority I set in PriorityQueue. By doing this, I made sure that the smallest string, rather than the one I put initially, would be served.

PriorityQueueExample.java

import java.util.PriorityQueue;
public class PriorityQueueExample
{
    public static void main(String[] args)
    {
        
        PriorityQueue<String> queue = 
            new PriorityQueue<String>(15, new MyComparator());
        queue.add("Tyrion Lannister");
        queue.add("Daenerys Targaryen");
        queue.add("Arya Stark");
        queue.add("Petyr 'Littlefinger' Baelish");
      
        /*
         * What I am doing here is removing the highest
         * priority element from Queue and displaying it.
         * The priority I have set is based on the string
         * length. The logic for it is written in Comparator
         */
        while (queue.size() != 0)
        {
            System.out.println(queue.poll());
        
        }
    }
}

MyComparator.java

import java.util.Comparator;

public class MyComparator implements Comparator<String>
{
   @Override
   public int compare(String x, String y)
   {
      return x.length() - y.length();
   }
}

Output:

Arya Stark
Tyrion Lannister
Daenerys Targaryen
Petyr 'Littlefinger' Baelish

Methods of PriorityQueue Class

add(E e), a boolean function, adds the element to the PriorityQueue.

void clear(): This function emptyes the PriorityQueue of all its entries.

Boolean contains(Element e): If the requested element is present in the queue, this method returns true.

Boolean Add() method is equivalent to Offer(E e).

E peek(): Returns the queue’s head (first entry).

E poll(): Returns the Queue’s head after removing it.

boolean remove(E e): If the supplied element is successfully deleted from the Queue, this function will return true. It returns false if the requested element isn’t in the queue.

Its size is returned by the int size() function.

object[] toArray(): Returns an array with every entry in the queue.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button