Kotlin List.asSequence() – Examples

Kotlin List.asSequence()

The Kotlin List asSequence() function is used to convert a given list into a Sequence object.

In Kotlin, a sequence returns values through its iterator, and the values are evaluated lazily.

Syntax

List.asSequence()

Returns a Sequence instance created from the List.

Example 1: Convert List to Sequence

In this example, we are given a list of numbers, and we have to convert this list to a sequence.

  1. Given a list of numbers in myList.
  2. Call asSequence() function on myList, and store the returned Sequence instance in mySequence.
  3. You may print the sequence to output using a For loop.

Program

fun main() {
    val myList = listOf(100, 200, 300, 400)

    val mySequence = myList.asSequence()

    for(item in mySequence) {
        println(item)
    }
}

Output

100
200
300
400