How to use PriorityQueue in java?

Tirupati Rao (bitbee)
2 min readSep 4, 2022

(Binary Heap)

Photo by davide ragusa on Unsplash

“Hi There”, We have learned about Binary Heap in our previous articles. If you miss those reads, recommend you to quickly go through the following reads about Heap.

In this article will see how Heap was implemented for PriorityQueue in Java

The PriorityQueue class implements the Queue Interface in Java. A PriorityQueue is beneficial when the objects are supposed to be processed based on 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 the construction time of the queue, depending on which constructor is used.

“So we can set a comparator through PriorityQueue Constructor to generate priority-based mInHeap or MaxHeap. Default comparator is with Natural sorting order (low to high or MinHeap based)”

1. MinHeap-based PriorityQueue Constructor (default behaviour):

PriorityQueue<Integer> max = new PriorityQueue<>((x, y) -> Integer.compare(x,y));

2. MaxHeap-based PriorityQueue Constructor:

PriorityQueue<Integer> max = new PriorityQueue<>((x, y) -> Integer.compare(y, x));

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

(Default behavior of PriorityQueue)

Java Implementation:

O/P:

Thanks for your read and 👏👏

Will see you in the next read.

#arraysinjava. #array #datastructures #codinginterviewquestions #codinginterview #faang #leetcode #animated #java #python #faang #motion

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Tirupati Rao (bitbee)
Tirupati Rao (bitbee)

Written by Tirupati Rao (bitbee)

Technical Writing | YT ▶️ BitBee | #Tech #Coding #interviews #bitbee #datastructures #algorithms #leetcode

No responses yet

Write a response