Kotlin是否有東西可以過濾一個集合并回傳匹配的索引?
例如,像Groovy的findIndexValues。
http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Iterable.html#findIndexValues(groovy.lang.Closure)
類似于:
fun <T>/span> List<T>. findIndexValues( predicate: (T) -> Boolean): List<Int> {
var indexValues = mutableListOf<Int> ()
this.forEachIndexed { index, it ->
if (predicate(it)) {
indexValues.add(index)
}
}
return indexValues
}
uj5u.com熱心網友回復:
我能想到的最簡單的方法是使用mapIndexedNotNull:
fun <T>/span> List<T>。 findIndexValues( predicate: (T) -> Boolean): List<Int> =
mapIndexedNotNull { i, t -> i.takeIf { predicate(t) } }
我不相信在標準庫中會有這樣的函式。
uj5u.com熱心網友回復:
據我所知,基本上有兩種簡單的方法。
//say there is a List x of Strings.
val x = listOf<String> ()
//I don't believe you are looking for this.
//string是x在索引處的所需字串。
for ((index, string) in x.withIndex() ) {
TODO()
}
//第二種方法是使用 filterIndexed。
/***。
* 回傳一個只包含與給定謂詞匹配的元素的串列。
* @Params: predicate - 函式,接收一個元素的索引和元素本身,并回傳元素上的predicate評估結果。
*/ */
x.filterIndexed { index, string ->
TODO()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/332807.html
標籤:
