Queues, stacks, and deques

suggest change

Kotlin doesn't have separate Queue and Stack classes in its standard library. It has one class that does both jobs: kotlin.collections.ArrayDeque, a double-ended queue ("deque", pronounced "deck") backed by a resizable circular array.

For the cases ArrayDeque doesn't cover, you use JDK classes:

Need Use
stack, queue or deque in single-threaded code kotlin.collections.ArrayDeque
always get the smallest (or largest) element next java.util.PriorityQueue
queue shared between threads, non-blocking java.util.concurrent.ConcurrentLinkedQueue / ConcurrentLinkedDeque
producer/consumer between threads, with waiting ArrayBlockingQueue, LinkedBlockingQueue
queue between coroutines kotlinx.coroutines.channels.Channel

ArrayDeque basics

ArrayDeque has addFirst/addLast to insert and removeFirst/removeLast to remove, all in amortized O(1). first() and last() peek without removing:

fun main() {
    val deque = ArrayDeque<Int>()
    deque.addLast(1)
    deque.addLast(2)
    deque.addFirst(0)
    println(deque)
    println("first=${deque.first()} last=${deque.last()} size=${deque.size}")
    println(deque.removeFirst())
    println(deque.removeLast())
    println(deque)
    println(deque[0])          // it's a List, so indexing works
    deque.clear()
    println(deque.removeFirstOrNull())
    println(deque.firstOrNull())
    try {
        deque.removeFirst()
    } catch (e: NoSuchElementException) {
        println("error: ${e.message}")
    }
}
[0, 1, 2]
first=0 last=2 size=3
0
2
[1]
1
null
null
error: ArrayDeque is empty.

Things to know:

Using ArrayDeque as a stack

For a stack, push with addLast, pop with removeLast and peek with last(). Using the end of the array means no elements are ever shifted.

A classic use is checking that brackets are balanced: push every opening bracket, and every closing bracket must match the one on top of the stack:

fun isBalanced(s: String): Boolean {
    val pairs = mapOf(')' to '(', ']' to '[', '}' to '{')
    val stack = ArrayDeque<Char>()
    for (c in s) {
        when (c) {
            '(', '[', '{' -> stack.addLast(c)
            ')', ']', '}' -> if (stack.removeLastOrNull() != pairs[c]) return false
        }
    }
    return stack.isEmpty()
}

fun main() {
    val stack = ArrayDeque<String>()
    stack.addLast("a")   // push
    stack.addLast("b")
    stack.addLast("c")
    println(stack)
    println(stack.last())       // peek
    println(stack.removeLast()) // pop
    println(stack.removeLast())
    println(stack)

    for (s in listOf("(a[b]{c})", "(]", "((", "")) {
        println("\"$s\" -> ${isBalanced(s)}")
    }
}
[a, b, c]
c
c
b
[a]
"(a[b]{c})" -> true
"(]" -> false
"((" -> false
"" -> true

removeLastOrNull() handles the "closing bracket with nothing open" case: it returns null, which never equals an opening bracket.

Stacks are also how you turn recursion into a loop when the recursion would be too deep for the call stack. Depth-first search, below, is an example.

Don't use java.util.Stack

java.util.Stack is a leftover from Java 1.0. It extends Vector, so every method is synchronized (slower, and no real help for thread safety), and it inherits list methods that let you insert in the middle. java.util.ArrayDeque has push/pop/peek methods too, but they work on the head, so it prints and iterates in the opposite order from Stack:

import java.util.Stack

fun main() {
    // legacy: synchronized, extends Vector, iterates bottom to top
    val legacy = Stack<Int>()
    legacy.push(1); legacy.push(2); legacy.push(3)
    println("Stack: $legacy pop=${legacy.pop()} peek=${legacy.peek()}")
    println(legacy.toList())

    // java.util.ArrayDeque used as a stack: push/pop work on the head
    val jdeque = java.util.ArrayDeque<Int>()
    jdeque.push(1); jdeque.push(2); jdeque.push(3)
    println("java.util.ArrayDeque: $jdeque pop=${jdeque.pop()} peek=${jdeque.peek()}")
    println(jdeque.toList())

    // Kotlin ArrayDeque used as a stack with addLast/removeLast
    val kdeque = ArrayDeque<Int>()
    kdeque.addLast(1); kdeque.addLast(2); kdeque.addLast(3)
    println("kotlin ArrayDeque: $kdeque pop=${kdeque.removeLast()} peek=${kdeque.last()}")
}
Stack: [1, 2, 3] pop=3 peek=2
[1, 2]
java.util.ArrayDeque: [3, 2, 1] pop=3 peek=2
[2, 1]
kotlin ArrayDeque: [1, 2, 3] pop=3 peek=2

All three pop 3 and then peek 2, but toList() gives different orders. Keep that in mind when you port Java code that converts a stack to a list.

Note that the unqualified name ArrayDeque means the Kotlin class (kotlin.collections is imported by default). To get the Java one, import java.util.ArrayDeque explicitly or write the full name, as above.

Using ArrayDeque as a queue

For a FIFO queue, enqueue with addLast and dequeue with removeFirst:

fun main() {
    val queue = ArrayDeque<String>()
    queue.addLast("job1")   // enqueue
    queue.addLast("job2")
    queue.addLast("job3")
    while (queue.isNotEmpty()) {
        val job = queue.removeFirst()   // dequeue
        println("processing $job, ${queue.size} left")
    }
}
processing job1, 2 left
processing job2, 1 left
processing job3, 0 left

Why not a MutableList?

You can treat a MutableList as a queue with add and removeAt(0) (or removeFirst()), but an ArrayList has to shift every remaining element one slot to the left on each removal from the front. That's O(n) per dequeue and O(n²) to drain the queue. ArrayDeque only moves its head index:

import kotlin.time.measureTime

fun main() {
    val n = 100_000
    repeat(2) {
        val list = MutableList(n) { it }
        val tList = measureTime { while (list.isNotEmpty()) list.removeAt(0) }

        val deque = ArrayDeque(List(n) { it })
        val tDeque = measureTime { while (deque.isNotEmpty()) deque.removeFirst() }

        println("ArrayList.removeAt(0): $tList, ArrayDeque.removeFirst(): $tDeque")
    }
}
ArrayList.removeAt(0): 521.754800ms, ArrayDeque.removeFirst(): 14.047500ms
ArrayList.removeAt(0): 579.489200ms, ArrayDeque.removeFirst(): 416.4us

Once the JIT has warmed up (second line), the deque is over 1000 times faster. Numbers vary by machine; see Benchmarks for how to measure properly with JMH.

The difference between a queue and a stack is exactly the difference between breadth-first search (BFS) and depth-first search (DFS). BFS visits nodes in order of distance from the start, so the first time it reaches the goal it has found a shortest path (in number of edges):

val graph = mapOf(
    "A" to listOf("B", "C"),
    "B" to listOf("D"),
    "C" to listOf("D", "E"),
    "D" to listOf("F"),
    "E" to listOf("F"),
    "F" to emptyList(),
)

fun shortestPath(start: String, goal: String): List<String>? {
    val queue = ArrayDeque(listOf(start))
    val cameFrom = mutableMapOf<String, String?>(start to null)
    while (queue.isNotEmpty()) {
        val node = queue.removeFirst()
        if (node == goal) {
            return generateSequence(goal) { cameFrom[it] }.toList().asReversed()
        }
        for (next in graph.getValue(node)) {
            if (next !in cameFrom) {
                cameFrom[next] = node
                queue.addLast(next)
            }
        }
    }
    return null
}

fun dfsOrder(start: String): List<String> {
    val stack = ArrayDeque(listOf(start))
    val visited = mutableSetOf<String>()
    val order = mutableListOf<String>()
    while (stack.isNotEmpty()) {
        val node = stack.removeLast()
        if (!visited.add(node)) continue
        order += node
        // push in reverse so the first neighbour is visited first
        for (next in graph.getValue(node).asReversed()) stack.addLast(next)
    }
    return order
}

fun main() {
    println(shortestPath("A", "F"))
    println(shortestPath("E", "A"))
    println(dfsOrder("A"))
}
[A, B, D, F]
null
[A, B, D, F, C, E]

cameFrom doubles as the "visited" set and records how each node was reached, so the path can be rebuilt by walking back from the goal with generateSequence. The DFS goes as deep as it can (A, B, D, F) before backtracking to C. Because it uses an explicit stack, it can handle graphs with millions of nodes without a StackOverflowError.

Deque tricks: sliding windows and ring buffers

Some problems need both ends. The sliding window maximum problem asks for the largest value in every window of k consecutive elements. A deque of indexes, kept so that their values decrease from front to back, solves it in O(n): old indexes leave from the front, and a new element evicts all smaller elements from the back, since they can never be a maximum again.

A ring buffer that keeps only the last N items, such as a command history, is just a deque that drops from the front when it's full:

// Maximum of every window of k consecutive elements, in O(n)
fun windowMax(xs: IntArray, k: Int): List<Int> {
    val idx = ArrayDeque<Int>()   // indexes, values decreasing from front to back
    val result = mutableListOf<Int>()
    for (i in xs.indices) {
        if (idx.isNotEmpty() && idx.first() <= i - k) idx.removeFirst()   // fell out of window
        while (idx.isNotEmpty() && xs[idx.last()] <= xs[i]) idx.removeLast()
        idx.addLast(i)
        if (i >= k - 1) result += xs[idx.first()]
    }
    return result
}

class RingBuffer<T>(private val capacity: Int) {
    private val items = ArrayDeque<T>(capacity)
    fun add(item: T) {
        if (items.size == capacity) items.removeFirst()
        items.addLast(item)
    }
    fun toList(): List<T> = items.toList()
}

fun main() {
    println(windowMax(intArrayOf(1, 3, -1, -3, 5, 3, 6, 7), 3))

    val recent = RingBuffer<String>(3)
    for (cmd in listOf("ls", "cd src", "vim a.kt", "make", "git status")) recent.add(cmd)
    println(recent.toList())
}
[3, 3, 5, 5, 6, 7]
[vim a.kt, make, git status]

Java's Queue and Deque interfaces

When you call Java APIs, or read Java code, you'll see the java.util.Queue and java.util.Deque interfaces. Each operation comes in two flavours: one that throws when the queue is empty (or full) and one that returns a special value:

Operation Throws Returns null / false
insert at tail add(e) offer(e)
remove head remove() poll()
look at head element() peek()

Deque adds First/Last versions of all of them: offerFirst, pollLast, peekFirst and so on.

import java.util.Deque
import java.util.LinkedList
import java.util.Queue

fun main() {
    val q: Queue<String> = java.util.ArrayDeque()
    q.offer("a")
    q.offer("b")
    println(q.peek())     // head, or null if empty
    println(q.poll())     // remove head, or null if empty
    println(q.poll())
    println(q.poll())
    println(q.peek())
    try {
        q.remove()        // throws when empty
    } catch (e: NoSuchElementException) {
        println("remove() threw ${e::class.simpleName}")
    }

    val d: Deque<Int> = java.util.ArrayDeque(listOf(1, 2, 3))
    println("${d.peekFirst()} ${d.peekLast()} ${d.pollFirst()} ${d.pollLast()} $d")

    try {
        java.util.ArrayDeque<String?>().add(null)
    } catch (e: NullPointerException) {
        println("java.util.ArrayDeque rejects null")
    }
    val ll = LinkedList<String?>()
    ll.add(null)
    println("LinkedList accepts null: $ll")
    val kd = ArrayDeque<String?>()
    kd.addLast(null)
    println("kotlin ArrayDeque accepts null: $kd, removeFirstOrNull=${kd.removeFirstOrNull()}")
}
a
a
b
null
null
remove() threw NoSuchElementException
1 3 1 3 [2]
java.util.ArrayDeque rejects null
LinkedList accepts null: [null]
kotlin ArrayDeque accepts null: [null], removeFirstOrNull=null

Since poll() uses null to mean "empty", java.util.ArrayDeque refuses null elements. Kotlin's ArrayDeque allows them if the type parameter is nullable, but then removeFirstOrNull() can't tell you whether the deque was empty or the element was null. Check isEmpty() first in that case, or better, avoid storing nulls.

LinkedList implements Deque too, but it allocates a node per element and has poor cache locality. There's no reason to choose it over an array-based deque.

PriorityQueue

A PriorityQueue doesn't return elements in insertion order but smallest first, according to their natural order or a Comparator. It's a binary heap: add and poll are O(log n), peek is O(1).

import java.util.PriorityQueue

data class Task(val name: String, val priority: Int)

fun main() {
    val nums = PriorityQueue(listOf(5, 1, 8, 3, 2))
    println(nums)            // heap order, not sorted!
    println(nums.peek())
    val out = mutableListOf<Int>()
    while (nums.isNotEmpty()) out += nums.poll()
    println(out)

    val maxHeap = PriorityQueue<Int>(compareByDescending { it })
    maxHeap.addAll(listOf(5, 1, 8, 3, 2))
    println(generateSequence { maxHeap.poll() }.toList())

    val tasks = PriorityQueue(compareBy<Task>({ it.priority }, { it.name }))
    tasks.add(Task("write docs", 3))
    tasks.add(Task("fix prod bug", 1))
    tasks.add(Task("review PR", 2))
    tasks.add(Task("deploy", 1))
    while (tasks.isNotEmpty()) println(tasks.poll())
}
[1, 2, 8, 3, 5]
1
[1, 2, 3, 5, 8]
[8, 5, 3, 2, 1]
Task(name=deploy, priority=1)
Task(name=fix prod bug, priority=1)
Task(name=review PR, priority=2)
Task(name=write docs, priority=3)

Watch out for these:

The comparators are built the same way as for sorting, which also shows how to use a bounded PriorityQueue to find the top N elements.

The textbook use is Dijkstra's shortest path algorithm. Instead of the O(n) "decrease key" operation, it's simpler to add a new entry and skip outdated ones when they come out:

import java.util.PriorityQueue

fun dijkstra(graph: Map<String, Map<String, Int>>, start: String): Map<String, Int> {
    val dist = mutableMapOf(start to 0)
    val pq = PriorityQueue<Pair<String, Int>>(compareBy { it.second })
    pq.add(start to 0)
    while (pq.isNotEmpty()) {
        val (node, d) = pq.poll()
        if (d > dist.getValue(node)) continue   // stale entry, skip
        for ((next, w) in graph[node].orEmpty()) {
            val nd = d + w
            if (nd < (dist[next] ?: Int.MAX_VALUE)) {
                dist[next] = nd
                pq.add(next to nd)
            }
        }
    }
    return dist
}

fun main() {
    val graph = mapOf(
        "A" to mapOf("B" to 4, "C" to 1),
        "C" to mapOf("B" to 2, "D" to 7),
        "B" to mapOf("D" to 1),
    )
    println(dijkstra(graph, "A").toSortedMap())
}
{A=0, B=3, C=1, D=4}

Queues shared between threads

ArrayDeque and PriorityQueue must not be used from several threads at once without a lock. When four threads each call addLast 10,000 times on one ArrayDeque, a test run produced several ArrayIndexOutOfBoundsExceptions inside ArrayDeque.ensureCapacity and a final size of 10,000 instead of 40,000. See Race conditions for why.

java.util.concurrent has thread-safe replacements. ConcurrentLinkedQueue (and ConcurrentLinkedDeque) is a lock-free, unbounded queue. poll() returns null when it's empty, which pairs nicely with ?: break:

import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.concurrent.thread

fun main() {
    val queue = ConcurrentLinkedQueue<Int>()
    val threads = (0 until 4).map { t ->
        thread { repeat(10_000) { queue.add(t * 10_000 + it) } }
    }
    threads.forEach { it.join() }
    println("size=${queue.size}")

    var sum = 0L
    while (true) {
        val x = queue.poll() ?: break
        sum += x
    }
    println("sum=$sum empty=${queue.isEmpty()}")
}
size=40000
sum=799980000 empty=true

size on ConcurrentLinkedQueue is O(n), because it walks the whole queue. Use isEmpty() if that's all you need.

Blocking queues for producers and consumers

A BlockingQueue adds operations that wait: take() blocks until an element is available and put() blocks until there's room. A bounded queue such as ArrayBlockingQueue gives you backpressure for free: a fast producer is slowed down to the speed of the consumer instead of filling up memory.

import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

const val DONE = -1   // "poison pill" that tells the consumer to stop

fun main() {
    val queue = ArrayBlockingQueue<Int>(2)   // holds at most 2 items

    val consumer = thread(name = "consumer") {
        while (true) {
            val item = queue.take()          // blocks while the queue is empty
            if (item == DONE) break
            Thread.sleep(50)                 // slow consumer
            println("consumed $item")
        }
    }

    for (i in 1..5) {
        queue.put(i)                         // blocks while the queue is full
        println("produced $i (queue size ${queue.size})")
    }
    queue.put(DONE)
    consumer.join()

    // non-blocking and timed variants
    val small = ArrayBlockingQueue<String>(1)
    println(small.offer("a"))                              // true
    println(small.offer("b"))                              // false, full
    println(small.offer("b", 100, TimeUnit.MILLISECONDS))  // false after 100 ms
    println(small.poll())                                  // a
    println(small.poll(100, TimeUnit.MILLISECONDS))        // null after 100 ms
}
produced 1 (queue size 1)
produced 2 (queue size 1)
produced 3 (queue size 2)
consumed 1
produced 4 (queue size 2)
consumed 2
produced 5 (queue size 2)
consumed 3
consumed 4
consumed 5
true
false
false
a
null

The exact interleaving of the first lines depends on thread scheduling, but the producer never gets more than two items ahead of the consumer. A blocking queue has no "closed" state, so the producer sends a special poison pill value to tell the consumer it's done.

Other implementations:

take() and put() block a whole thread. In coroutines code use a Channel from kotlinx.coroutines instead: send and receive suspend instead of blocking, a channel can be bounded (Channel(capacity = 2)), and it can be closed, so the consumer can just write for (item in channel) with no poison pill.

Summary

For the other collection types, see Collections.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents