Priority Queue Introduction

priority queue introduction

What is a Priority Queue in Java ?

A Priority Queue in java programming is a data structure, in which priority is set already . In priority queue we work with the data depending  on some priority .For example  if we want to delete an element from the queue, the data with the highest priority will be deleted first, in similar way if we are inserting data in the queue, it will be arranged in the queue depending upon its priority.

Let’s see how a priority queue in java works.

Priority Queue is other form of  normal queue with following properties.

  1. Each and Every item has a priority associated with it.
  2. An element which has  high priority is dequeued first as compared with element with low priority.
  3. If by chance elements have the same priority, they are served according to their order in the queue.
  4. A Priority Queue can be implemented using various different data structures like
    • Arrays
    • Linked List
    •  Heap

Priority Queue Operation

  • Enqueue(): This function is for inserting an element in a queue
  • Dequeue(): This function is used for deleting an element in a queue, based on the priority of the element.
  • show():  This will print all elements of the Queue.

How is a Priority Queue implemented in Java ?

There are three different data structures that we can use to implement Priority Queue in java:

  • Array
  • Linked List
  • Heap

Java code to implement priority queue using queue class 

// Java program to implement priority queue 
// using queue class 
import java.util.*;

class prepinsta {

  // Main Method
  public static void main(String[] args)
  {

    // Creating a priority queue
    PriorityQueue<Stringpq = new PriorityQueue<>();
    pq.add(“hello”);
    pq.add(“hiii”);
    pq.add(“by”);
    System.out.println(“Priority Queue is : “ + pq);

    
    String value = pq.peek();
    System.out.println(“Element accessed is : “ + value);
  }
}
OUTPUT :

Priority Queue is: [by, hiii, hello]
Element accessed is: by

APPLICATIONS OF PRIORITY QUEUES :

 Following are some applications of Priority Queue:

  • Dijkstra’s shortest path algorithm.
  • Data Compression
  • Heap Sort
  • Prim’s Algorithm
  • Operating System: Interrupt Handling.