first, last
first
, last
These functions return the first and the last element of the collection correspondingly. You can also use them with a predicate; in this case, they return the first or the last element that matches the given predicate.
If a collection is empty or doesn't contain elements matching the predicate, the functions throw NoSuchElementException
.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val first = numbers.first() // 2
val last = numbers.last() // 3
val firstEven = numbers.first { it % 2 == 0 } // 4
val lastOdd = numbers.last { it % 2 != 0 } // 5
println("Numbers: $numbers")
println("First $first, last $last, first even $firstEven, last odd $lastOdd")
}
- Defines a collection of numbers.
- Picks the first element.
- Picks the last element.
- Picks the first even element.
- Picks the last odd element.
firstOrNull
, lastOrNull
These functions work almost the same way with one difference: they return null
if there are no matching elements.
fun main() {
val words = listOf("foo", "bar", "baz", "faz") // 1
val empty = emptyList<String>() // 2
val first = empty.firstOrNull() // 3
val last = empty.lastOrNull() // 4
val firstF = words.firstOrNull { it.startsWith('f') } // 5
val firstZ = words.firstOrNull { it.startsWith('z') } // 6
val lastF = words.lastOrNull { it.endsWith('f') } // 7
val lastZ = words.lastOrNull { it.endsWith('z') } // 8
println("Empty list: first is $first, last is $last")
println("Word list: first item starting with 'f' is $firstF, first item starting with 'z' is $firstZ")
println("Word list: last item ending with 'f' is $lastF, last item ending with 'z' is $lastZ")
}
- Defines a collection of words.
- Defines an empty collection.
- Picks the first element from empty collection. It supposed to be
null
. - Picks the last element from empty collection. It supposed to be
null
as well. - Picks the first word starting with 'f'.
- Picks the first word starting with 'z'.
- Picks the last word ending with 'f'.
- Picks the last word ending with 'z'.