Skip to main content

Posts

Showing posts with the label stream

sequences in Kotlin

Introduction Sequences in Kotlin are similar to that of the stream s in Java, where in the evaluation happens lazily and the volume of data processed in each step in the chain are reducing based on the met criteria. Sample Let us consider the below given sample data class data class Car ( val model : String , val year : Int ) We can create a collection of cars so that we can evaluate both and understand the difference between collections and sequence   in Kotlin var cars = listOf ( Car ( "Toyota" , 2021), Car ( model = "Tesla-S" , 2022), Car ( "Mercedes - Maybach" , 2022) ) Sequence In the below given snippet of code, we are performing the filtering of cars by name and then printing the year println ( cars . asSequence (). filter { it . model == "Toyota" } . map { it . year } This produces the output as given below kotlin.sequences.TransformingSequence@b97c004a This is because the sequence is lazy and is not evaluated as there is