Home > OS >  How to remove String from a ListOf Strings in Kotlin?
How to remove String from a ListOf Strings in Kotlin?

Time:12-08

I have a listOf Strings

val help = listOf("a","b","c")

And want to remove b from the list but not using index because I will get Strings randomly like this

val help = listOf("c","a","b")

How to do this?

CodePudding user response:

You can filter the List using the condition item does not equal "b", like…

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

Output:

[a, b, c]
[a, c]

CodePudding user response:

Lists by default aren't mutable. You should use mutable lists instead if you want that. Then you can simply do

val help = mutableListOf("a","b","c")
help.remove("b")

or you can do it like this if help really needs to be a non-mutable list

val help = listOf("a","b","c")
val newHelp = help.toMutableList().remove("b")

using a filter like in deHaar's answer is also possible

  • Related