PriorityQueue in Java

 A queue data structure that retrieves the data element based on priority. The priority can be ahighest or lowest. It can implemented as “queue” interface in java.

How it orders the elements?

It follows natural for ordering. For numbers, it follows ascending order. For strings, it follows lexicographic order.

Program:

Built in packages: java.uti.PriorityQueue, java.util.Comparator;

Steps to follow:

  • ·       Create an object for PriorityQueue.
  • ·       Insert the elements to the priority queue and display it.
  • ·       Delete the head of the queue and displayed it.
  • ·       The head of the queue is displayed, it is retrieved but not deleted.
  • ·       Display the PriorityQueue after polling.
  • ·       Let us develop a PriorityQueue with comparator in the descending order and display it.

Here, is the java program.

import java.util.PriorityQueue;

import java.util.Comparator;

public class PQueueEg {

    public static void main(String[] args) {

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

        pQ.add(34);

        pQ.add(45);

        pQ.add(56);

        pQ.add(67);

        System.out.println("Priority Queue is displayed here: " + pQ);

        System.out.println("The Polled element is: " + pQ.poll());

        System.out.println("The Peek element is: " + pQ.peek());

        System.out.println("Priority Queue after polling: " + pQ);

        PriorityQueue<Integer> pQDes = new PriorityQueue<>(Comparator.reverseOrder());

        pQDes.add(150);

        pQDes.add(54);

        pQDes.add(89);

        System.out.println("PriorityQueue (descending): " + pQDes);

    }

}

Output:

C:\raji\blog>javac PQueueEg.java

C:\raji\blog>java PQueueEg

Priority Queue is displayed here: [34, 45, 56, 67]

The Polled element is: 34

The Peek element is: 45

Priority Queue after polling: [45, 67, 56]

PriorityQueue (descending): [150, 54, 89]

Priority queue is efficient in retrieving data. Keep coding!!!.Feel free to ask the doubts in the comment section.

No comments:

Post a Comment