Skip to content

Instantly share code, notes, and snippets.

@StefMa
Last active January 8, 2018 07:25
Show Gist options
  • Save StefMa/47255a8dd66c0934bea4d583edcbb7e2 to your computer and use it in GitHub Desktop.
Save StefMa/47255a8dd66c0934bea4d583edcbb7e2 to your computer and use it in GitHub Desktop.
Kotlin Sequence

List Test:

Map Human(name=Stefan, age=12)
Map Human(name=Amy, age=1)
Filter Stefan
Filter Amy
[Stefan]

Sequence Test:

Map Human(name=Stefan, age=12)
Filter Stefan
Map Human(name=Amy, age=1)
Filter Amy
[Stefan]

List Performance:

Map Human(name=Stefan, age=12)
Map Human(name=Amy, age=1)
Stefan

Sequence Performance:

Map Human(name=Stefan, age=12)
Stefan
class Test {
data class Human(val name: String, val age: Int)
@Test
fun list() {
val toList = listOf(Human("Stefan", 12), Human("Amy", 1))
.map { println("Map $it"); it.name }
.filter { println("Filter $it"); it.startsWith("S") }
println(toList)
}
@Test
fun sequence() {
val toList = listOf(Human("Stefan", 12), Human("Amy", 1)).asSequence()
.map { println("Map $it"); it.name }
.filter { println("Filter $it"); it.startsWith("S") }
.toList()
println(toList)
}
@Test
fun list_performance() {
val toList = listOf(Human("Stefan", 12), Human("Amy", 1))
.map { println("Map $it"); it.name }
.first { it.startsWith("S") }
println(toList)
}
@Test
fun sequence_performance() {
val toList = listOf(Human("Stefan", 12), Human("Amy", 1)).asSequence()
.map { println("Map $it"); it.name }
.first { it.startsWith("S") }
println(toList)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment