The asSequence() extension function for sets in Kotlin creates a Sequence instance that wraps the original set, returning its elements when being iterated. This is useful for performing sequence operations that are lazy and efficient.
The syntax of Set.asSequence() extension function is:
fun <T> Set<T>.asSequence(): Sequence<T>
This asSequence() extension function of Set creates a Sequence instance that wraps the original set returning its elements when being iterated.
Set.asSequence() returns value of type Sequence
.
In Kotlin, we can use the asSequence()
function to treat a set as a sequence and perform lazy operations on it.
For example,
asSequence()
function to get a sequence from the set.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.asSequence().filter { it % 2 == 0 }.toList()
println("Even numbers: $evenNumbers")
}
Even numbers: [2, 4]
In Kotlin, we can use the asSequence()
function to treat a set as a sequence and apply a map operation on its elements.
For example,
asSequence()
function to get a sequence from the set.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry")
val lengths = fruits.asSequence().map { it.length }.toList()
println("Lengths of fruits: $lengths")
}
Lengths of fruits: [5, 6, 6]
In Kotlin, we can use the asSequence()
function to treat an empty set as a sequence.
For example,
asSequence()
function to get a sequence from the empty set.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val evenNumbers = emptySet.asSequence().filter { it % 2 == 0 }.toList()
println("Even numbers in empty set: $evenNumbers")
}
Even numbers in empty set: []
In this Kotlin tutorial, we learned about asSequence() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.