Queue
A Queue
is a collection interface in Kotlin that represents a data structure that stores elements in a linear order, and follows the First In, First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed.
Creating a Queue
In Kotlin, a queue can be created using the Queue
interface:
val queue: Queue<Type> = Collection()
queue
is a variable that is of typeQueue
.Type
is the data type of the elements within the queue.Collection
is the collections class that is used to implement the queue. Some possible implementations include aLinkedList
,ArrayDeque
, andPriorityQueue
.
Below, a queue of string elements is created using an instance of the LinkedList
collection:
val queue: Queue<String> = LinkedList()
Adding Elements to a Queue
The .add()
method can be used to add elements to a queue:
import java.util.*fun main() {// Create a queue of stringsval queue: Queue<String> = LinkedList()// Add elements to the queuequeue.add("apple")queue.add("banana")queue.add("orange")println(queue)}
The output for the above code will be:
[apple, banana, orange]
Removing Elements from a Queue
The .remove()
method can be used to remove elements from a queue:
import java.util.*fun main() {// Create a queue of stringsval queue: Queue<String> = LinkedList()// Add elements to the queuequeue.add("apple")queue.add("banana")queue.add("orange")println(queue)val a = queue.remove()val b = queue.remove()val c =queue.remove()println(queue)print(a,b,c)}fun print(a: String, b: String, c: String) {println("First element removed is: $a ")println("Second element removed is: $b ")println("Third element removed is: $c ")}
The output for the above code will be:
[apple, banana, orange][]First element removed is: appleSecond element removed is: bananaThird element removed is: orange
In the above code, the elements were removed from the queue using .remove()
method. In addition, a variable was created to hold each element that was removed.
Peeking at Elements in a Queue
The .peek()
method can be used to print out the first element in a queue:
import java.util.*fun main() {val queue: Queue<String> = LinkedList()queue.add("apple")queue.add("banana")queue.add("orange")println(queue)val frontElement = queue.peek()println("The front element peeked is: $frontElement")}
The output for the above code will be:
[apple, banana, orange]The front element peeked is: apple
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.