Kotlin Tutorials

Kotlin Set find()
Syntax & Examples

Set.find() extension function

The find() extension function in Kotlin searches for the first element in a set that matches the given predicate and returns it. If no such element is found, it returns null.


Syntax of Set.find()

The syntax of Set.find() extension function is:

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

This find() extension function of Set returns the first element matching the given predicate, or null if no such element was found.

Parameters

ParameterOptional/RequiredDescription
predicaterequiredA function that takes an element and returns true if the element matches the condition.

Return Type

Set.find() returns value of type T?.



✐ Examples

1 Finding the first even number

Using find() to search for the first even number in a set.

For example,

  1. Create a set of integers.
  2. Define a predicate function that returns true for even numbers.
  3. Use find() to search for the first even number in the set.
  4. Print the resulting number.

Kotlin Program

fun main() {
    val numbers = setOf(1, 3, 5, 6, 7, 8)
    val firstEven = numbers.find { it % 2 == 0 }
    println(firstEven)
}

Output

6

2 Finding the first string with length greater than 2

Using find() to search for the first string with a length greater than 2 in a set.

For example,

  1. Create a set of strings.
  2. Define a predicate function that returns true for strings with a length greater than 2.
  3. Use find() to search for the first string with a length greater than 2 in the set.
  4. Print the resulting string.

Kotlin Program

fun main() {
    val strings = setOf("a", "ab", "abc", "abcd")
    val firstLongString = strings.find { it.length > 2 }
    println(firstLongString)
}

Output

"abc"

3 Finding the first non-null value

Using find() to search for the first non-null value in a set.

For example,

  1. Create a set containing integers and null values.
  2. Define a predicate function that returns true for non-null values.
  3. Use find() to search for the first non-null value in the set.
  4. Print the resulting value.

Kotlin Program

fun main() {
    val mixedSet: Set<Int?> = setOf(null, 2, null, 4, 5)
    val firstNonNull = mixedSet.find { it != null }
    println(firstNonNull)
}

Output

2

Summary

In this Kotlin tutorial, we learned about find() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.