Kotlin List asSequence()
Syntax & Examples
Syntax of List.asSequence()
The syntax of List.asSequence() extension function is:
fun <T> Iterable<T>.asSequence(): Sequence<T>
This asSequence() extension function of List creates a Sequence instance that wraps the original collection returning its elements when being iterated.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing integers from 1 to 5. - We use the
asSequence()
function to convertlist1
into a sequence and store it insequence
. - We convert the sequence back to a list using
toList()
and print it. - The output is the same as
list1
, which is [1, 2, 3, 4, 5].
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5);
val sequence = list1.asSequence();
println(sequence.toList());
}
Output
[1, 2, 3, 4, 5]
2 Example
In this example,
- We create a list named
list2
containing characters 'a' to 'e'. - We use the
asSequence()
function to convertlist2
into a sequence and store it insequence
. - We convert the sequence back to a list using
toList()
and print it. - The output is the same as
list2
, which is ['a', 'b', 'c', 'd', 'e'].
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf('a', 'b', 'c', 'd', 'e');
val sequence = list2.asSequence();
println(sequence.toList());
}
Output
[a, b, c, d, e]
3 Example
In this example,
- We create a list named
list3
containing strings "apple", "banana", and "cherry". - We use the
asSequence()
function to convertlist3
into a sequence and store it insequence
. - We convert the sequence back to a list using
toList()
and print it. - The output is the same as
list3
, which is ["apple", "banana", "cherry"].
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "cherry");
val sequence = list3.asSequence();
println(sequence.toList());
}
Output
[apple, banana, cherry]
Summary
In this Kotlin tutorial, we learned about asSequence() extension function of List: the syntax and few working examples with output and detailed explanation for each example.