Sequences in kotlin - devrath/KotlinAlchemy GitHub Wiki
Background
There are many ways to handle a group of items.
Collections and Sequences provide many utilities.
Eagerly with the collections and Lazily with sequences.
Difference b/w Eagerly and Lazy -- Explained with example
Depends on when the transformation is performed on the collection
Collection use Eagerly
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.
Sequences use Lazily
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
More differences
Feature
Collection in Kotlin
Sequence in Kotlin
Mutability
Collections can be mutable (MutableList, MutableSet, etc.)
Sequences are immutable
Evaluation
Evaluated eagerly
Evaluated lazily
Use Case
Suitable for general-purpose data manipulation and storage
Suitable for processing large datasets or infinite streams
Functions
Supports various functions like map, filter, reduce
Supports similar functions, but they are lazily evaluated
Processing
May process the entire collection even if not needed
Processes elements only as needed
Performance
Generally faster for small collections
Generally more efficient for large datasets
API
Rich set of APIs for common operations
Limited set of APIs due to lazy evaluation
Examples
kotlin val list = mutableListOf(1, 2, 3)
kotlin val sequence = sequenceOf(1, 2, 3)
Performance comparison on collection and sequence
Whether you use collection or sequence, The order of operators matters.
When used with small data collections or sequences does not matter.
When used with large data, The sequence is the better choice.
Example Demo
data classShape(valname:String , varcolor:String)
val listOfShapes =listOf(
Shape(name ="Circle", color ="Green"),
Shape(name ="Rectangle", color ="Purple"),
Shape(name ="Triangle", color ="Red"),
Shape(name ="Triangle", color ="Yellow")
)
funmain(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"
}
}