Kotlin List.first() – Examples

Kotlin List.first()

The Kotlin List.first() function is used to retrieve the first element of a list or the first element satisfying a given predicate.

Syntax

List.first()

Returns the first element.

List.first(predicate)

Returns the first element matching the given predicate(condition).

The return type would be same as that of the returned element.

Example 1: Getting the first element of a list

In this example, we shall take an integer list, and get the first element of this list using List.first(), without passing any predicate.

Program

fun main() {
    val numbers = listOf(10, 20, 30, 40, 50)
    val firstNumber = numbers.first()
    println(firstNumber)
}

Output

10

Example 2: Getting the first element that satisfies a condition

In this example, we shall take a list of strings, and get the first string element that starts with the character 'b', using List.first() function with the predicate.

Program

fun main() {
    val fruits = listOf("apple", "banana", "cherry", "berry")
    val firstBFruit = fruits.first{ it.startsWith('b') }
    println(firstBFruit)
}

Output

banana