Kotlin Queue Example
In this tutorial, I'll demonstrate Kotlin Queue example..
What is Queue?
A queue is an ordered collection of items, First In First Out (FIFO) in which new items are added at one end, known as the "rear", and existing items are removed at the other end, known as the "front".
Kotlin - Queue Methods
Below methods are available as part of the Queue.
enqueue()
: Add item.dequeue()
: Remove item.peek()
: Access item.size()
: Get the total number of items available in Queue.isEmpty()
: Verify if Queue is empty.
Kotlin Queue
package com.techgeeknext
import java.util.Queue
import java.util.LinkedList
fun main(args: Array<String>)
{
val employees: Queue<String> = LinkedList<String>(listOf("AAA", "XYZ", "YYY"))
employees.add("ZZZ")
for(employee in employees)
{
println(employee) //Output: [AAA, XYZ, ,YYY, ZZZ]
}
// Remove AAA
// Removing item from empty queue will throNoSuchElementException
println(employees.remove())
// Remove XYZ
// Removing item from empty queue will give null
println(employees.poll()) // Remove XYZ
println("First item in Queue: " + employees.peek()) // Output - YYY
}
Kotlin Queue - Peek and Poll
package com.techgeeknext
import java.util.Queue
import java.util.LinkedList
fun main(args: Array<String>)
{
val employees: Queue<String> = LinkedList<String>(listOf("AAA", "XYZ", "YYY"))
employees.add("ZZZ")
for(employee in employees)
{
println(employee) //Output: [AAA, XYZ, ,YYY, ZZZ]
}
// Removing or polling item from empty queue will give null
println(employees.pollFirst()) // Remove First item AAA
// accessing first item from empty queue will give null
println(employees.peekFirst()) // Output: XYZ
}