Kotlin Set asSequence()
Syntax & Examples
Set.asSequence() extension function
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.
Syntax of Set.asSequence()
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.
Return Type
Set.asSequence() returns value of type Sequence
.
✐ Examples
1 Using asSequence() to perform lazy operations on a set
In Kotlin, we can use the asSequence()
function to treat a set as a sequence and perform lazy operations on it.
For example,
- Create a set of integers.
- Use the
asSequence()
function to get a sequence from the set. - Perform a filter operation to retain only even numbers.
- Convert the sequence back to a list and print the result using the
println
function.
Kotlin Program
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")
}
Output
Even numbers: [2, 4]
2 Using asSequence() to map elements of a set
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,
- Create a set of strings.
- Use the
asSequence()
function to get a sequence from the set. - Perform a map operation to convert each string to its length.
- Convert the sequence back to a list and print the result using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry")
val lengths = fruits.asSequence().map { it.length }.toList()
println("Lengths of fruits: $lengths")
}
Output
Lengths of fruits: [5, 6, 6]
3 Using asSequence() with an empty set
In Kotlin, we can use the asSequence()
function to treat an empty set as a sequence.
For example,
- Create an empty set of integers.
- Use the
asSequence()
function to get a sequence from the empty set. - Perform a filter operation to retain only even numbers (although there are none).
- Convert the sequence back to a list and print the result using the
println
function.
Kotlin Program
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")
}
Output
Even numbers in empty set: []
Summary
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.