A priority-queue is an “abstract data type”. It is similar to a normal queue, but certain elements take priority when they are polled (perhaps for a print statement).

Why do we need priority queues?

Let’s say you’re in the hospital with a sore-throat at midnight. You have waited your turn, and now you are the front of the queue that the  emergency staff need to see. There are 5 people behind you with broken bones and 3rd degree burns. This is ultimately where the queue fails in real-life situations.

Namely because someone is likely to pass-away during the time it takes the nurses to source a throat lozenge and a paracetamol for you.

Priority queues allow you prioritise certain elements. Which is great for the people bleeding-out profusely, but not so great for your sore throat.

How Do You Create A Priority Queue In Java?

[java] //This creates an empty Priority Queue with the default 11 element capacity.
PriorityQueue exampleQueue = new PriorityQueue();

//This creates a queue with capacity for 5 elements.
PriorityQueue fiveElementQueue = new PriorityQueue(5);
[/java]

Simple Priority Queue Methods

How to add an Object to a Priority Queue

[java] //First create some objects..
String feeling = “sad”;
String not = “popular”;

//Add the objects to it
exampleQueue.add(feeling);
exampleQueue.add(not);
[/java]

How to return the front of Priority Queue

[java] //This will return the front of the queue without dequeuing (removing) the element.
exampleQueue.peek();
[/java]

How return your Priority Queue as an Array

[java] //This will return the front of the queue without dequeuing (removing) the element.
exampleQueue.toArray();
[/java]

How to return the head (the ordered first in the queue; poll)

[java] //This will dequeue and return the front of the queue based on priority.
exampleQueue.poll();
[/java]
Leave a Reply
You May Also Like

Forex Money Management: How to Manage Your Money when Trading Forex

I’m not a finance professional, don’t take my advice, this article is…

Java Scanner: How to Read Text Files in Java

The Scanner is super useful for taking user inputs. However, you might…

YouTube: How to Make Money with “Top 10” YouTube Channels

In today’s post I’m going to show you how to build a…

CMC: How to Trade with CMC Markets

CMC markets is a “multi-award winning platform” with over 10,000 instruments and…