在列表中搜索某个元素并将其删除

时间:2019-12-03 07:54:46

标签: string list kotlin

我在kotlin中有一个List<String>,其中包含以下元素

"Bank", "of", "Luxemburg", "Orange", "County"

如果List包含"of",我该如何搜索?

如何获取position中的"of",然后从列表中删除它?

4 个答案:

答案 0 :(得分:4)

首先请确保您的列表是可变列表:

val list = mutableListOf("bank", "of" , "Luxemburg", "Orange", "country")

或者如果您已经有一个列表:

val newList = list.toMutableList()

然后执行此操作:

list.remove("bank")

输出:

[of, Luxemburg, Orange, country]

如果同一列表中有更多复印值,请执行以下操作:

 list.removeAll(listOf("Luxemburg"))

输出:

[bank, of, Luxemburg, Orange, country, Luxemburg]
[bank, of, Orange, country]

答案 1 :(得分:2)

如果您要删除列表中找到的第一个"of",则remove就足够了。如果要删除每次出现的"of",请使用removeIf甚至是removeAll

fun main() {
    val l: MutableList<String>
                = mutableListOf("Bank", "of", "Luxemburg", "of", "Orange", "of", "County")
    val m: MutableList<String>
                = mutableListOf("Bank", "of", "Luxemburg", "of", "Orange", "of", "County")
    println(l)
    // remove first "of" found
    l.remove("of")
    println(l)
    // remove every element that equals "of"
    l.removeIf { it == "of" }
    println(l)

    println("————————————————————————————————")
    // use removeAll
    println(m)
    m.removeAll { it == "of" }
    println(m)
}

输出为

[Bank, of, Luxemburg, of, Orange, of, County]
[Bank, Luxemburg, of, Orange, of, County]
[Bank, Luxemburg, Orange, County]
————————————————————————————————
[Bank, of, Luxemburg, of, Orange, of, County]
[Bank, Luxemburg, Orange, County]

答案 2 :(得分:2)

如果您只想返回没有“ of”的元素,则可以对其进行过滤

val list = listOf("bank", "of" , "Luxemburg", "Orange", "country")
val result = list.filter { it != "of" }

答案 3 :(得分:0)

我认为这可行: list.indexOf("of").also { if (it != -1) list.removeAt(index) }