Kotlin Tutorials

Kotlin Set findLast()
Syntax & Examples

Set.findLast() extension function

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


Syntax of Set.findLast()

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

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

This findLast() extension function of Set returns the last 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.findLast() returns value of type T?.



✐ Examples

1 Finding the last even number

Using findLast() to search for the last 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 findLast() to search for the last even number in the set.
  4. Print the resulting number.

Kotlin Program

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

Output

8

2 Finding the last string with length greater than 2

Using findLast() to search for the last 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 findLast() to search for the last 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 lastLongString = strings.findLast { it.length > 2 }
    println(lastLongString)
}

Output

"abcd"

3 Finding the last non-null value

Using findLast() to search for the last 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 findLast() to search for the last 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 lastNonNull = mixedSet.findLast { it != null }
    println(lastNonNull)
}

Output

5

Summary

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