问题
I would like to filter an array into an array of every nth item. For examples:
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()
}
Is there an idiomatic way to do this using for example Kotlin's .filter() and without A) provisioning a new ArrayList and B) manually iterating with a for/in loop?
回答1:
filterIndexed
function is suited exactly for this case:
array.filterIndexed { index, value -> index % n == 0 }
回答2:
Use 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 }
来源:https://stackoverflow.com/questions/46867406/kotlin-filter-lambda-array-using-iteration-index