📜  kotlin queue - Kotlin (1)

📅  最后修改于: 2023-12-03 15:17:09.484000             🧑  作者: Mango

Kotlin Queue

Queue is a data structure that follows the First-In-First-Out (FIFO) principle. Kotlin provides different implementations of the queue, including LinkedList and PriorityQueue.

LinkedList Queue

LinkedList is a sequential list that can be modified at both ends, making it an ideal structure for implementing a Queue. Here's how to create a Queue using a LinkedList:

val queue = LinkedList<String>()

queue.add("first element")
queue.add("second element")
queue.add("third element")

println(queue.peek()) // prints "first element"
println(queue.poll()) // removes and returns "first element"
println(queue.poll()) // removes and returns "second element"
println(queue.poll()) // removes and returns "third element"

In the above example, we create a LinkedList and add elements to it using the add method. The peek method returns the first element in the queue without removing it, while the poll method removes and returns the first element.

PriorityQueue

Priority queue is an ordered queue that orders elements according to their priority. Elements with higher priority come out of the queue first. In Kotlin, we can use the Comparator interface to define the priority of elements. Here's a PriorityQueue example:

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

val queue = PriorityQueue<Task> { a, b ->
    when {
        a.priority > b.priority -> -1
        a.priority == b.priority -> 0
        else -> 1
    }
}

queue.add(Task("one", 1))
queue.add(Task("three", 3))
queue.add(Task("two", 2))

println(queue.peek()) // prints "three"
println(queue.poll()) // removes and returns "three"
println(queue.poll()) // removes and returns "two"
println(queue.poll()) // removes and returns "one"

In the above example, we define a Task class with name and priority fields. We use a lambda expression to define the priority of Tasks in the PriorityQueue. Finally, we add Tasks to the queue using the add method and poll them using the poll method.

Conclusion

Kotlin provides different implementations of the queue, allowing developers to choose the best one for their needs. LinkedList is a simple and effective implementation for most use cases, while PriorityQueue is useful for ordering elements according to their priority.