Kotlin Array asSequence()

Kotlin Array asSequence()

In Kotlin, the Array asSequence() function is used to convert this array into a sequence. It allows you to work with arrays using the functions and features provided by the Sequence interface.

This function is beneficial when you need to perform lazy evaluation and transformation operations on the elements of the array, potentially improving performance for large datasets.

In this tutorial, we’ll explore the syntax of the asSequence() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array asSequence() function is:

fun <T> Array<out T>.asSequence(): Sequence<T>

Examples

1. Using asSequence() for Transformation

In this example, we’ll use asSequence() to convert an array into a sequence and perform a lazy transformation operation on its elements.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 2, 3, 4, 5)
    
    // Converting array to sequence using asSequence
    val numbersSequence: Sequence<Int> = numbersArray.asSequence()
    
    // Using sequence operations to square each number lazily
    val squaredNumbers = numbersSequence.map { it * it }
    
    // Printing the original array and the result
    println("Original Array: ${numbersArray.joinToString(", ")}")
    println("Squared Numbers: ${squaredNumbers.joinToString(", ")}")
}

Output

Original Array: 1, 2, 3, 4, 5
Squared Numbers: 1, 4, 9, 16, 25

In this example, we use asSequence() to convert an array of numbers into a sequence. We then use the sequence operation map to lazily square each number. The original array and the transformed result are printed to the console.

2. Using asSequence() for Filtering

In this example, we’ll use Array asSequence() function to convert a given array of strings wordsArray into a sequence wordsSequence and perform a lazy filtering operation on the sequence.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "orange", "grape", "kiwi")
    
    // Converting array to sequence using asSequence
    val wordsSequence: Sequence<String> = wordsArray.asSequence()
    
    // Using sequence operations to filter words starting with 'a' lazily
    val filteredWords = wordsSequence.filter { it.startsWith('a') }
    
    // Printing the original array and the result
    println("Original Words: ${wordsArray.joinToString(", ")}")
    println("Filtered Words: ${filteredWords.joinToString(", ")}")
}

Output

Original Words: apple, banana, orange, grape, kiwi
Filtered Words: apple

In this example, we use asSequence() to convert an array of words into a sequence. We then use the sequence operation filter to lazily retain only the words starting with ‘a’. The original array and the filtered result are printed to the console.

Summary

In this tutorial, we’ve covered the asSequence() function in Kotlin arrays, its syntax, and how to use it to convert an array into a sequence.