SowingFiber
SowingFiber

Reputation: 1244

Search for a certain element in a List and delete it

I have a List<String> in kotlin which contains the following elements

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

How do I search the List if it contains "of"?

How can I get the position of "of" and then delete it from the list?

Upvotes: 0

Views: 75

Answers (4)

goedi
goedi

Reputation: 2083

If you just want the elements back without "of" you can filter them

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

Upvotes: 2

Dak28
Dak28

Reputation: 259

First be sure that your list is a mutable list:

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

Or if you already have a list:

val newList = list.toMutableList()

then do this:

list.remove("bank")

output:

[of, Luxemburg, Orange, country]

If you have more copy value in same list do it:

 list.removeAll(listOf("Luxemburg"))

output:

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

Upvotes: 4

deHaar
deHaar

Reputation: 18558

In case you want to remove the first "of" found in the list, then remove will be sufficient. If you want to remove every occurrence of "of", then use removeIf or maybe even 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)
}

The output is

[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]

Upvotes: 2

parohy
parohy

Reputation: 2180

I think this could work: list.indexOf("of").also { if (it != -1) list.removeAt(index) }

Upvotes: 0

Related Questions