使用迭代索引的Kotlin过滤器Lambda数组 [英] Kotlin filter lambda array using iteration index

查看:103
本文介绍了使用迭代索引的Kotlin过滤器Lambda数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个数组过滤到第n个项目的数组中.例如:

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()
}

是否有一种惯用的方式使用例如Kotlin的.filter()而不使用A)设置新的ArrayList和B)手动循环for/in循环?

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?

推荐答案

filterIndexed函数完全适合这种情况:

filterIndexed function is suited exactly for this case:

array.filterIndexed { index, value -> index % n == 0 }

这篇关于使用迭代索引的Kotlin过滤器Lambda数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆