Nat*_*han 6 arrays lambda kotlin
我想将数组过滤成每个第n项的数组.举些例子:
fun getNth(array: Array<Any>, n: Int): Array<Any> {
val newList = ArrayList<Any>()
for (i in 0..array.size) {
if (i % n == 0) {
newList.add(array[i])
}
}
return newList.toArray()
}
Run Code Online (Sandbox Code Playgroud)
有没有惯用的方法来使用例如Kotlin的.filter()而没有A)配置新的ArrayList和B)手动迭代for/in循环?
Ily*_*lya 17
filterIndexed 功能完全适合这种情况:
array.filterIndexed { index, value -> index % n == 0 }
Run Code Online (Sandbox Code Playgroud)
使用Array.withIndex():
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/with-index.html:
array.withIndex().filter { (i, value) -> i % n == 0 }.map { (i, value) -> value }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5161 次 |
| 最近记录: |