partition
所在位置是kotlin.collections.partition
,其相關用法介紹如下。
用法一
inline fun DoubleArray.partition(
predicate: (Double) -> Boolean
): Pair<List<Double>, List<Double>>
inline fun BooleanArray.partition(
predicate: (Boolean) -> Boolean
): Pair<List<Boolean>, List<Boolean>>
將原始數組拆分為一對列表,其中 first
list 包含 predicate 產生 true
的元素,而 second
list 包含 predicate 產生 false
的元素。
例子:
import kotlin.test.*
fun main(args: Array<String>) {
//sampleStart
val array = intArrayOf(1, 2, 3, 4, 5)
val (even, odd) = array.partition { it % 2 == 0 }
println(even) // [2, 4]
println(odd) // [1, 3, 5]
//sampleEnd
}
輸出:
[2, 4] [1, 3, 5]
用法二
將原始集合拆分為一對列表,其中 first
list 包含 predicate 產生 true
的元素,而 second
list 包含 predicate 產生 false
的元素。
例子:
fun main(args: Array<String>) {
//sampleStart
data class Person(val name: String, val age: Int) {
override fun toString(): String {
return "$name - $age"
}
}
val list = listOf(Person("Tom", 18), Person("Andy", 32), Person("Sarah", 22))
val result = list.partition { it.age < 30 }
println(result) // ([Tom - 18, Sarah - 22], [Andy - 32])
//sampleEnd
}
輸出:
([Tom - 18, Sarah - 22], [Andy - 32])
相關用法
- Kotlin partition用法及代碼示例
- Kotlin padEnd用法及代碼示例
- Kotlin padStart用法及代碼示例
- Kotlin plus用法及代碼示例
- Kotlin associateBy用法及代碼示例
- Kotlin all用法及代碼示例
- Kotlin map用法及代碼示例
- Kotlin filterNot用法及代碼示例
- Kotlin reduceRight用法及代碼示例
- Kotlin Random.Default用法及代碼示例
- Kotlin Byte.inc用法及代碼示例
- Kotlin getValue用法及代碼示例
- Kotlin Double.dec用法及代碼示例
- Kotlin windowedSequence用法及代碼示例
- Kotlin contentToString用法及代碼示例
- Kotlin groupByTo用法及代碼示例
- Kotlin commonPrefixWith用法及代碼示例
- Kotlin MatchResult.Destructured用法及代碼示例
- Kotlin Delegates.notNull用法及代碼示例
- Kotlin ifBlank用法及代碼示例
- Kotlin filterNotTo用法及代碼示例
- Kotlin getOrPut用法及代碼示例
- Kotlin Triple.<init>用法及代碼示例
- Kotlin Duration.toString用法及代碼示例
- Kotlin windowed用法及代碼示例
注:本文由純淨天空篩選整理自kotlinlang.org大神的英文原創作品 kotlin.collections.partition。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。