Kotlin Sequence last Function

The last function in Kotlin is used to return the last element of a sequence that matches a given predicate. It is part of the Kotlin standard library and provides a way to find and retrieve the last element that satisfies a condition.

Table of Contents

  1. Introduction
  2. last Function Syntax
  3. Understanding last
  4. Examples
    • Basic Usage
    • Finding the Last Element in a Sequence of Strings
    • Using last with Custom Objects
    • Chaining last with Other Functions
  5. Real-World Use Case
  6. Conclusion

Introduction

The last function allows you to find and retrieve the last element in a sequence that matches a given predicate. This is useful for scenarios where you need to locate and use the last element that satisfies a specific condition.

last Function Syntax

The syntax for the last function is as follows:

fun <T> Sequence<T>.last(): T
fun <T> Sequence<T>.last(predicate: (T) -> Boolean): T

Parameters:

  • predicate: (Optional) A lambda function that defines the condition each element in the sequence must satisfy.

Returns:

  • The last element that matches the given predicate, or the last element of the sequence if no predicate is provided.

Throws:

  • NoSuchElementException if no element matches the predicate or if the sequence is empty and no predicate is provided.

Understanding last

The last function works by iterating through the sequence and applying the predicate (if provided) to each element. It returns the last element that satisfies the predicate. If no predicate is provided, it returns the last element of the sequence.

Examples

Basic Usage

To demonstrate the basic usage of last, we will create a sequence of integers and retrieve the last element.

Example

fun main() {
    val numbers = sequenceOf(1, 2, 3, 4, 5)
    val lastNumber = numbers.last()
    println(lastNumber) // Output: 5
}

Output:

5

Finding the Last Element in a Sequence of Strings

This example shows how to find the last string in a sequence that has more than 5 characters.

Example

fun main() {
    val names = sequenceOf("Arjun", "Bhaskar", "Chitra", "Deepak", "Esha")
    val lastLongName = names.last { it.length > 5 }
    println(lastLongName) // Output: Deepak
}

Output:

Deepak

Using last with Custom Objects

You can use the last function to find the last element of custom objects that satisfies a specific condition.

Example

data class Person(val name: String, val age: Int)

fun main() {
    val people = sequenceOf(
        Person("Arjun", 25),
        Person("Bhaskar", 30),
        Person("Chitra", 22),
        Person("Deepak", 28),
        Person("Esha", 26)
    )
    val lastAdult = people.last { it.age >= 25 }
    println(lastAdult) // Output: Person(name=Esha, age=26)
}

Output:

Person(name=Esha, age=26)

Chaining last with Other Functions

The last function can be chained with other sequence functions to perform more complex operations before retrieving the last element.

Example

fun main() {
    val numbers = sequenceOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    val lastEvenNumberGreaterThanFive = numbers.filter { it > 5 }
                                                .last { it % 2 == 0 }
    println(lastEvenNumberGreaterThanFive) // Output: 10
}

Output:

10

Real-World Use Case

Finding the Last Available Product

In real-world applications, the last function can be used to find the last available product from a sequence of products.

Example

data class Product(val name: String, val available: Boolean)

fun main() {
    val products = sequenceOf(
        Product("Laptop", false),
        Product("Smartphone", true),
        Product("Tablet", false),
        Product("Headphones", true)
    )

    val lastAvailableProduct = products.last { it.available }
    println(lastAvailableProduct) // Output: Product(name=Headphones, available=true)
}

Output:

Product(name=Headphones, available=true)

Conclusion

The last function in Kotlin provides used for finding and retrieving the last element in a sequence that matches a given predicate. By understanding and using the last function, you can efficiently manage and process data in your Kotlin applications, ensuring that you can locate and use the last elements that satisfy specific conditions according to your requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top