我有一個 listOf Strings
val help = listOf("a","b","c")
并想b從list但不使用索引中洗掉,因為我會像這樣隨機獲取字串
val help = listOf("c","a","b")
這該怎么做?
uj5u.com熱心網友回復:
您可以List使用條件item does not equal "b"進行過濾,例如...
fun main(args: Array<String>) {
// example list
val help = listOf("a","b","c")
// item to be dropped / removed
val r = "b"
// print state before
println(help)
// create a new list filtering the source
val helped = help.filter { it != r }.toList()
// print the result
println(helped)
}
輸出:
[a, b, c]
[a, c]
uj5u.com熱心網友回復:
默認情況下,串列是不可變的。如果需要,您應該改用可變串列。然后你可以簡單地做
val help = mutableListOf("a","b","c")
help.remove("b")
或者你可以這樣做,如果help真的需要一個非可變串列
val help = listOf("a","b","c")
val newHelp = help.toMutableList().remove("b")
也可以使用像 deHaar's answer 中的過濾器
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/375959.html
標籤:科特林
