Kotlin Array.find()

Kotlin Array.find() function

In Kotlin, the Array.find() function is used to find the first element in the array that satisfies the given predicate. It returns the first element that matches the predicate or null if no such element is found.

In this tutorial, we’ll explore the syntax of the find() function and provide examples of its usage in Kotlin arrays, both with and without a predicate.

Syntax

The syntax of the Array.find() function is as follows:

fun <T> Array<out T>.find(predicate: (T) -> Boolean): T?

where

ParameterDescription
predicateA lambda function that takes the element of the array as an argument and returns true or false.
Parameter of Array.find() function

Examples for Array.find() function

1. Finding the First Even Number in the Array

In this example, we’ll use find() to find the first even number from given array of integers numbersArray.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 3, 5, 7, 8, 9, 10, 11)

    // Finding the first even number
    val firstEvenNumber = numbersArray.find { it % 2 == 0 }

    // Printing the original array and the result
    println("Numbers Array\n${numbersArray.joinToString(", ")}\n")
    println("First Even Number\n$firstEvenNumber")
}

Output

Numbers Array
1, 3, 5, 7, 8, 9, 10, 11

First Even Number
8

2. No Element found for the given Predicate

In this example, we’ll use Array.find() function with a predicate such that there is no element in the array that satisfies the condition.

We shall try to find the integer in the array numbersArray that is exactly divisible by 25.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 3, 5, 7, 8, 9, 10, 11)

    // Finding the first even number
    val result = numbersArray.find { it % 25 == 0 }

    // Printing the original array and the result
    println("Numbers Array\n${numbersArray.joinToString(", ")}\n")
    println("Result\n$result")
}

Output

Numbers Array
1, 3, 5, 7, 8, 9, 10, 11

Result
null

Summary

In this tutorial, we’ve covered the Array.find() function in Kotlin arrays, its syntax, and how to use it to find the first element based on a predicate.