How to Create & Manipulate Java Priority Queues

373
0
SHARE

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]

Related:  How Buy Bitcoin Safely & Securely (Video Guides)