In this episode of Fragmented, we go back to learning some Kotlin and look at the Iterable like data structure introduced called "Sequences". What is a sequence? How is it different from Iterable? When should I use it?
Eager evaluation:
val lst = listOf(1, 2)
val lstMapped: List = lst.map { print("$it "); it * it }
print("before sum ")
val sum = lstMapped.sum()
// prints "1 2 before sum"
Lazy evaluation:
val seq = sequenceOf(1, 2)
val seqMapped: Sequence = seq.map { print("$it "); it * it }
print("before sum ")
val sum = seqMapped.sum()
// prints "before sum 1 2"
Source stackoverflow.com answer
Notice that at each chain operation, a new temporary list is created:
data class Person(val name: String, val age: Int)
fun main(args: Array) {
val people =
listOf(Person("Chris Martin", 31),
Person("Will Champion", 32),
Person("Jonny Buckland", 33),
Person("Guy Berryman", 34),
Person("Mhris Cartin", 30))
println(people
.filter { it.age > 30 } // new temp. list
.map {
it.name.split(" ").map {it[0]}.joinToString("")
} // new temp. list
.map { it.toUpperCase() }) // new temp. list
}
Using a sequence:
println(people
.asSequence() // convert to sequence
.filter { it.age > 30 } // lazy eval (intermediate op)
.map {
it.name.split(" ").map {it[0]}.joinToString("")
} // lazy eval (intermediate op)
.map { it.toUpperCase() } // lazy eval (intermediate op)
.toList() // terminal operation
)
Without a terminal operation, Sequences won't print anything:
val seq = sequenceOf(1, 2, 3)
println(seq) // prints address
println(seq.toList()) // [1, 2, 3]
You can't pick an index from a sequence:
println(seq[0]) // throws ERROR "No get method providing array access"
println(seq.toList()[0]) // 1
Copyright 2024 Spec Network, Inc.