In this tutorial, we’re gonna look at overview of Kotlin Queue interface and some examples that show how to work with Kotlin Queue such as define, initialize, add or remove items, peek, poll methods.
Related Post: Kotlin Priority Queue tutorial with examples
Contents
Overview
A Queue is just like a queue in real-life. It’s a First In First Out (FIFO) data structure. New elements will be added at the back and removed from the front.
- Adding an element at the back is called Enqueue.
- Removing an element from the front is called Dequeue.
Kotlin Queue interface which is part of Collections framework. Diagram below shows hierarchy of Queue interface in Collections.
You can see that the Queue
is just an interface, so we need a concrete implementation.
LinkedList
class implements the Queue interface => we can use it as a Queue
.
Define a Queue in Kotlin
To define a Queue, we create a new LinkedList
object.
package com.bezkoder.kotlin.queue
import java.util.Queue
import java.util.LinkedList
fun main(args: Array<String>) {
val nums: Queue<Int> = LinkedList<Int>()
val names: Queue<String> = LinkedList<String>()
val persons: Queue<Person> = LinkedList<Person>()
}
Initialize a Queue in Kotlin
val nums: Queue<Int> = LinkedList<Int>(listOf(1, 2, 3))
val names: Queue<String> = LinkedList<String>(listOf("Jack", "Adam", "Katherin"))
val persons: Queue<Person> =
LinkedList<Person>(listOf(Person("Jack", 27), Person("Adam", 28), Person("Katherin", 19)))
println(nums)
println(names)
println(persons)
Output:
[1, 2, 3]
[Jack, Adam, Katherin]
[Person(name=Jack, age=27), Person(name=Adam, age=28), Person(name=Katherin, age=19)]
Kotlin Queue add items
We add new elements to the Queue (enqueue operation) using add() method
val names: Queue<String> = LinkedList<String>()
names.add("Jack")
names.add("Adam")
names.add("Katherin")
names.add("Helen")
names.add("Watson")
println(names)
Output:
[Jack, Adam, Katherin, Helen, Watson]
Kotlin Queue remove items
We can remove an element from the Queue (dequeue operation) using remove() method.
This method will throw NoSuchElementException
if the Queue is empty.
// Queue: [Jack, Adam, Katherin]
var name: String?;
name = names.remove() // Jack
println(names)
// [Adam, Katherin]
name = names.remove() // Adam
println(names)
// [Katherin]
name = names.remove() // Katherin
println(names)
// []
name = names.remove()
/*
Exception in thread "main" java.util.NoSuchElementException
at java.util.LinkedList.removeFirst(Unknown Source)
at java.util.LinkedList.remove(Unknown Source)
at com.bezkoder.kotlin.queue.AppKt.main(app.kt:42)
*/
Kotlin Queue poll
The poll() method is similar to remove()
(dequeue operation), but it returns null
if the Queue is empty instead of throwing an exception.
// Queue: [Jack, Adam, Katherin]
var name: String?;
name = names.poll() // Jack
println(names)
// [Adam, Katherin]
name = names.poll() // Adam
println(names)
// [Katherin]
name = names.poll() // Katherin
println(names)
// []
name = names.poll() // null
Kotlin Queue peek
The examples show you how to:
- Check if a Queue is empty using
- Get the size of a Queue
- Check if a Queue contains an element and find its index
- Get the element at the front of the Queue (without removing it) using element() or peek()
The difference between element()
and peek()
is that, if the Queue is empty, element()
throws NoSuchElementException
while peek()
returns null
.
package com.bezkoder.kotlin.queue
import java.util.Queue
import java.util.LinkedList
fun main(args: Array<String>) {
val names: Queue<String> = LinkedList<String>()
names.add("Jack")
names.add("Adam")
names.add("Katherin")
println("Queue: " + names)
println("is Queue empty? : " + names.isEmpty())
println("Size of Queue : " + names.size)
val name = "Adam"
if (names.contains(name)) {
println("Queue contains " + name);
println("-at index " + names.indexOf(name));
} else {
println("Queue doesn't contain " + name);
}
var first = names.element()
println("First item in Queue: " + first);
first = names.peek()
println("First item in Queue: " + first);
}
Output:
Queue: [Jack, Adam, Katherin]
is Queue empty? : false
Size of Queue : 3
Queue contains Adam
-at index 1
First item in Queue: Jack
First item in Queue: Jack
Iterate a Queue in Kotlin
The examples shows you several ways to iterate over a Queue:
- forEach() method
- simple for loop
iterator()
iterator()
andforEachRemaining()
method
package com.bezkoder.kotlin.queue
import java.util.Queue
import java.util.LinkedList
fun main(args: Array) {
val names: Queue = LinkedList()
names.add("Jack")
names.add("Adam")
names.add("Katherin")
println("== forEach() ==")
names.forEach { name -> print(">$name ") }
println("\n== simple for loop ==")
for (name in names) {
print(">$name ")
}
println("\n== iterator ==")
var queueIterator = names.iterator()
while (queueIterator.hasNext()) {
val name = queueIterator.next()
print(">$name ")
}
println("\n== iterator with forEachRemaining ==")
queueIterator = names.iterator()
queueIterator.forEachRemaining { name -> print(">$name ") }
}
Output:
== forEach() ==
>Jack >Adam >Katherin
== simple for loop ==
>Jack >Adam >Katherin
== iterator ==
>Jack >Adam >Katherin
== iterator with forEachRemaining ==
>Jack >Adam >Katherin
Conclusion
Today we’ve known what is a Queue data structure, how to define, initialize, create a Queue in Kotlin, way to add item to a Queue or remove items from the Queue. You also know some methods to access Queue data and iterate over a Queue.
How about a Queue in that items will be ordered? Let’s explore in the tutorial:
Kotlin Priority Queue tutorial with examples
Happy Learning! See you again.
Very helpful Thanks!
Veгy nicе post. I hope you write again vеry soon for more Kotlin tutorial!
Good tutorial! Thanks!
Thanks for share this Kotlin tutorial. It is quite helpful to me.
Best regards,
Harrell Henneberg