Kotlin List first()
Syntax & Examples
Syntax of List.first()
There are 2 variations for the syntax of List.first() extension function. They are:
1.
fun <T> List<T>.first(): TThis extension function returns the first element.
2.
fun <T> Iterable<T>.first(predicate: (T) -> Boolean): TThis extension function returns the first element matching the given predicate.
✐ Examples
1 Example
In this example,
- We create a list named
list1containing integers. - We use the
first()function onlist1to get the first element. - The first element of
list1is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val result = list1.first()
println(result)
}Output
1
2 Example
In this example,
- We create a list named
list2containing strings. - We use the
firstfunction onlist2with a predicate that finds the first string with length greater than 5. - The first string with length greater than 5 in
list2is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf("apple", "banana", "cherry")
val result = list2.first { it.length > 5 }
println(result)
}Output
banana
3 Example
In this example,
- We create a list named
list3containing characters. - We use the
firstfunction onlist3with a predicate that finds the first lowercase character. - The first lowercase character in
list3is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf('a', 'b', 'c', 'd', 'e')
val result = list3.first { it.isLowerCase() }
println(result)
}Output
a
Summary
In this Kotlin tutorial, we learned about first() extension function of List: the syntax and few working examples with output and detailed explanation for each example.