Omar Younis
Omar Younis

Reputation: 21

how to remove an element at a specified location from a list in Kotlin?

I have a problem, I have a list containing integer elements, and I want to remove one element and return a list without that removed element... Is there such a function in Kotlin that let me do that? or should I do it myself? I tried to use the filter function, make a variable equals to the elements in the place I want to remove, and then keep the elements that don't equal to that one but it was not like I wanted because some times it removes more than one element that equal to the one I want to remove, just like this :

...

for (i in 0 until array.size){
var removed = array[i] 
array.filter{ it != removed }
.
.
. }

I'm kind of new to Kotlin, so can anyone help me here :)?

Upvotes: 2

Views: 4204

Answers (2)

Joffrey
Joffrey

Reputation: 37660

If you want a collection that has the flexibility of removing elements from the middle, you should probably not use an array directly. Consider using lists instead (List, MutableList).

If you want to change (mutate) a list, you have to have a MutableList in the first place, then you can call remove(element) on it to remove the element equal to the one you passed:

val list: MutableList<String> = mutableListOf("a", "b", "c", "d")
list.remove("c")
println(list) // prints [a, b, d]

You can also call removeAt(index) on it to remove an element at a specific index:

val list: MutableList<String> = mutableListOf("a", "b", "c", "d")
list.removeAt(2) // 2 is the index of element "c"
println(list) // prints [a, b, d]

It is usually advised to avoid mutable data structures when performance is not an issue. For instance, you can return a new list instead of mutating the original list. In that case, you don't need a MutableList (use a plain List), and you can simply use the minus operator:

val list1 = listOf("a", "b", "c", "d")
val list2 = list1 - "c"
println(list2) // prints [a, b, d]

I don't think there is an existing function for index-based subtraction in a List, but you can use filterIndexed and compare the index with the one you want to remove:

val list1 = listOf("a", "b", "c", "d")
val list2 = list1.filterIndexed { i, _ -> i != 2 } // 2 is the index of element "c"
println(list2) // prints [a, b, d]

Upvotes: 3

Wendy
Wendy

Reputation: 1

Remove the first occurrence of a given item from a list:

Your list must be mutable. If you have an unmutable list, cast it to a mutable one or reassign it to a new variable.

val list : List<Int> = listOf(1, 2, 3, 4, 5)
println(list) // prints [1, 2, 3, 4, 5]
var output = list.toMutableList()
output.remove(3) // remove element 3
println(output) // prints [1, 2, 4, 5]

Upvotes: 0

Related Questions