0
0
KotlinHow-ToBeginner · 3 min read

How to Implement Queue in Kotlin: Simple Guide with Examples

In Kotlin, you can implement a queue using the ArrayDeque class which provides efficient FIFO operations. Alternatively, you can create a custom queue class using a MutableList to add elements at the end and remove from the front.
📐

Syntax

The simplest way to implement a queue in Kotlin is by using ArrayDeque<T>. It supports addLast() to enqueue and removeFirst() to dequeue elements.

Alternatively, you can use a MutableList<T> and manage the queue operations manually by adding elements at the end and removing from the front.

kotlin
val queue = ArrayDeque<String>()
queue.addLast("first")  // Enqueue
val item = queue.removeFirst()  // Dequeue
💻

Example

This example shows how to use ArrayDeque as a queue to add and remove elements in FIFO order.

kotlin
fun main() {
    val queue = ArrayDeque<Int>()
    queue.addLast(10)  // Enqueue 10
    queue.addLast(20)  // Enqueue 20
    queue.addLast(30)  // Enqueue 30

    println("Queue after enqueuing: $queue")

    val first = queue.removeFirst()  // Dequeue
    println("Dequeued element: $first")
    println("Queue after dequeuing: $queue")
}
Output
Queue after enqueuing: [10, 20, 30] Dequeued element: 10 Queue after dequeuing: [20, 30]
⚠️

Common Pitfalls

One common mistake is using a List instead of a MutableList which is immutable and cannot add or remove elements.

Another pitfall is removing elements from the front of a MutableList using removeAt(0), which is inefficient because it shifts all elements. Using ArrayDeque avoids this problem.

kotlin
fun wrongQueue() {
    val list = listOf(1, 2, 3)  // Immutable list
    // list.add(4)  // Error: Unresolved reference: add
}

fun inefficientQueue() {
    val list = mutableListOf(1, 2, 3)
    list.removeAt(0)  // Works but slow for large lists
}

fun efficientQueue() {
    val queue = ArrayDeque<Int>()
    queue.addLast(1)
    queue.removeFirst()  // Fast dequeue
}
📊

Quick Reference

OperationMethodDescription
EnqueueaddLast(element)Add element to the end of the queue
DequeueremoveFirst()Remove and return the first element
Peekfirst()View the first element without removing
Check emptyisEmpty()Returns true if queue has no elements

Key Takeaways

Use ArrayDeque in Kotlin for an efficient and simple queue implementation.
Enqueue with addLast() and dequeue with removeFirst() for FIFO behavior.
Avoid using immutable lists or removing from front of MutableList due to inefficiency.
ArrayDeque provides fast operations without shifting elements.
Always check if the queue is empty before dequeuing to avoid exceptions.