`removeAt` implies passing an index though ?
# announcements
b
removeAt
implies passing an index though ?
đź‘Ť 1
k
Yes, I'm looking for something like
list.withoutElementAt(index)
.
s
Based on @adam-mcneilly’s answer: val index = 3 val answers = listOf(“Yes”, “No”, “Maybe”) val yesNoList = answers - answers[index] println(yesNoList) // [Yes, No]
k
Problem with that is that
answers[index]
isn't guaranteed to be the first occurrence of that value.
@adam-mcneilly
c
Also,
removeAt
should be (almost) constant time while
-
is linear
p
This operation cannot be done in constant time as new list should be created and all elements except one should be copied to new list. So it will always take linear time.
I would advise to use
MutableList
instead.
or you can create your own extension function, here are 3 different ways to implement it:
Copy code
fun <T> List<T>.withoutElementAt(index: Int): List<T>
    = this.toMutableList().apply { removeAt(index) }
Copy code
fun <T> List<T>.withoutElementAt1(index: Int)
        = this.asSequence()
            .withIndex()
            .filter { it.index != index}
            .map { it.value }
            .toList()
Copy code
fun <T> List<T>.withoutElementAt2(index: Int): List<T> {
    val result = mutableListOf<T>()
    for (i in this.indices) {
        if (i != index) result.add(this[i])
    }
    return result
}
@karelpeeters
ops, didn’t see discussion below…
k
Haha, thanks for helping anyway!
c
@Pavlo Liapota This could be made constant time with a new
List
representation that I described in the follow up conversation