Skip to main content

How to retrieve the first or last element of a LinkedList in Kotlin

How to retrieve the first or last element of a LinkedList in Kotlin.

Here's a step-by-step tutorial on how to retrieve the first or last element of a LinkedList in Kotlin.

Step 1: Create a LinkedList

First, we need to create a LinkedList in Kotlin. To do this, you can use the LinkedList class provided by the Kotlin standard library. Here's an example of creating a LinkedList:

val linkedList = LinkedList<String>()

Step 2: Add elements to the LinkedList

Next, we need to add some elements to the LinkedList. You can use the add method of the LinkedList to add elements at the end of the list. Here's an example of adding elements to the LinkedList:

linkedList.add("Apple")
linkedList.add("Banana")
linkedList.add("Orange")

Step 3: Retrieve the first element

To retrieve the first element of the LinkedList, you can use the first property of the LinkedList. This property returns the first element of the list, or throws a NoSuchElementException if the list is empty. Here's an example of retrieving the first element:

val firstElement = linkedList.first
println("First element: $firstElement")

Step 4: Retrieve the last element

To retrieve the last element of the LinkedList, you can use the last property of the LinkedList. This property returns the last element of the list, or throws a NoSuchElementException if the list is empty. Here's an example of retrieving the last element:

val lastElement = linkedList.last
println("Last element: $lastElement")

Step 5: Handle empty LinkedList

If the LinkedList is empty, trying to retrieve the first or last element using the first or last property will throw a NoSuchElementException. To handle this situation, you can use the firstOrNull and lastOrNull properties instead. These properties return the first or last element if the list is not empty, or null if the list is empty. Here's an example of handling an empty LinkedList:

val emptyLinkedList = LinkedList<String>()
val firstElementOrNull = emptyLinkedList.firstOrNull
val lastElementOrNull = emptyLinkedList.lastOrNull

if (firstElementOrNull != null) {
println("First element: $firstElementOrNull")
} else {
println("LinkedList is empty")
}

if (lastElementOrNull != null) {
println("Last element: $lastElementOrNull")
} else {
println("LinkedList is empty")
}

That's it! You've learned how to retrieve the first or last element of a LinkedList in Kotlin.