Kotlin filter lambda array using iteration index

北城余情 提交于 2021-02-07 12:19:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!