-
Notifications
You must be signed in to change notification settings - Fork 24
Sequences in kotlin
Devrath edited this page Feb 28, 2024
·
6 revisions
- There are many ways to handle a group of items.
-
Collections
andSequences
provide many utilities. -
Eagerly
with thecollections
andLazily
withsequences
.
- Depends on when the transformation is performed on the collection
- On each operation, A new collection is formed and modified based on the operator's nature.
- Operations on the collections are implemented using
inline
functions. - Collection creates a new list for each operation.
- Sequence is created based on the iterator of the original collection.
- So we need to add
asSequence()
- The operations are added to the list of operations to be performed but the operations are not performed immediately
- Instead, the Terminal operator is applied first if it contains it, and thus map is not applied if it contains it.
- Also new copy is not created on each operator invocation.
- Each operation is not an
inline function
. - Sequence creates a new object for every operation
- Whether you use
collection
orsequence
, The order of operators matters. - When used with small data
collections
orsequences
does not matter. - When used with large data, The
sequence
is the better choice.
data class Shape(val name:String , var color: String)
val listOfShapes = listOf(
Shape(name = "Circle", color = "Green"),
Shape(name = "Rectangle", color = "Purple"),
Shape(name = "Triangle", color = "Red"),
Shape(name = "Triangle", color = "Yellow")
)
fun main(args: Array<String>) {
val shapesWithYellowColor = listOfShapes
// Convert the color to yellow
.map {
it.copy(color = "Yellow")
}
// Pick the first rectangle
.first{
it.name == "Rectangle"
}
val shapesWithRedColor = listOfShapes.asSequence()
// Convert the color to yellow
.map {
it.copy(color = "Red")
}
// Pick the first rectangle
.first{
it.name == "Triangle"
}
}