https://kotlinlang.org logo
#announcements
Title
# announcements
b

bj0

12/04/2017, 8:46 PM
removeAt
implies passing an index though ?
👍 1
k

karelpeeters

12/04/2017, 8:47 PM
Yes, I'm looking for something like
list.withoutElementAt(index)
.
s

stephan_marshay

12/04/2017, 8:50 PM
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

karelpeeters

12/04/2017, 8:50 PM
Problem with that is that
answers[index]
isn't guaranteed to be the first occurrence of that value.
@adam-mcneilly
c

cedric

12/04/2017, 8:53 PM
Also,
removeAt
should be (almost) constant time while
-
is linear
p

Pavlo Liapota

12/05/2017, 10:52 AM
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

karelpeeters

12/05/2017, 11:01 AM
Haha, thanks for helping anyway!
c

cedric

12/05/2017, 5:19 PM
@Pavlo Liapota This could be made constant time with a new
List
representation that I described in the follow up conversation
2 Views