Kotlin Priority Queue Example
In this tutorial, I'll demonstrate Kotlin Priority Queue and explain with examples.
What is Priority Queue?
Priority Queue is a queue extension with the properties listed below.
- There is a priority assigned to each item.
- A high-priority element is dequeued first, followed by a low-priority element.
- When two components have the same priority, they are served in the order in which they appeared in the queue.
Kotlin - PriorityQueue Function
add(element: E)
oroffer(element: E)
: Both are functions ofPriorityQueue
used to add item to the queue.PriorityQueue
implements two interfaces -collections
(uses add) andQueue
(uses offer).peek()
: Get the head of the item from the queue without deleting it.poll()
: Remove/delete the head of the item from the queue.
Priority Queue in Kotlin
package com.techgeeknext
import java.util.PriorityQueue
fun main(args: Array<String>)
{
//Highest Priority Queue
val employeesIds = PriorityQueue<Int> {
a, b -> b - a
}
// Add 33, 65, 78 , 2 to the employeesIds
employeesIds.offer(33)
employeesIds.offer(65)
employeesIds.offer(78)
employeesIds.add(2)
//peek will not remove the item
employeesIds.peek() // output: 78
while(!employeesIds.isEmpty()) {
employeesIds.poll() // output: 78, 65, 33, 2
}
}