This example shows how to get first and the last elements of the list in Kotlin.
Kotlin List first and last elements
The example creates a list of fruits. We get the first and the last elements of the list.
package net.sourcecodeexamples.kotlin fun main() { val fruits = listOf("banana", "mango", "apple", "orange") val w1 = fruits.first() println(w1) val w2 = fruits.last() println(w2) val w3 = fruits.findLast { w -> w.startsWith('a') } println(w3) val w4 = fruits.first { w -> w.startsWith('o') } println(w4) }
Output:
banana orange apple orange
We get the first element with first():
val w1 = words.first()
We get the last element with last():
val w2 = words.last()
We retrieve the last element of the list that starts with 'a' with findLast():
val w3 = words.findLast { w -> w.startsWith('a') }
We retrieve the first element of the list that starts with 'o' with first():
val w4 = words.first { w -> w.startsWith('o') }
Comments
Post a Comment