inline fun <T> Sequence<T>.partition( predicate: (T) -> Boolean ): Pair<List<T>, List<T>>
Splits the original sequence into pair of lists, where first list contains elements for which predicate yielded true
, while second list contains elements for which predicate yielded false
.
The operation is terminal.
import kotlin.test.*
fun main(args: Array<String>) {
//sampleStart
fun fibonacci(): Sequence<Int> {
// fibonacci terms
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, ...
return generateSequence(Pair(0, 1), { Pair(it.second, it.first + it.second) }).map { it.first }
}
val (even, odd) = fibonacci().take(10).partition { it % 2 == 0 }
println(even) // [0, 2, 8, 34]
println(odd) // [1, 1, 3, 5, 13, 21]
//sampleEnd
}
© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/partition.html