Lukasz Kalnik
07/18/2022, 3:02 PMmapNotNull { if (it == removeMe) null else it }
doesn't support lists with nullable elements.
In my case the elements have unique IDs, so I could also filter {}
or dropWhile {}
based on ID, but the names are not obviously suggesting that only one element gets removed.
Do we have to do toMutableList().remove(removeMe).toList()
?Joffrey
07/18/2022, 3:03 PMLukasz Kalnik
07/18/2022, 3:05 PMJoffrey
07/18/2022, 3:05 PMequals()
, which is likely more expensive than filtering based on the ID (unless you overrode equals()
to use the ID)Lukasz Kalnik
07/18/2022, 3:05 PMJoffrey
07/18/2022, 3:06 PMLukasz Kalnik
07/18/2022, 3:06 PMtoMutableList().removeIf { it.id == removeMe.id }.toList()
?Joffrey
07/18/2022, 3:07 PMval newList = oldList.filter { it.id != removeMe.id }
But I agree it doesn't express the intent so wellephemient
07/18/2022, 3:07 PMLukasz Kalnik
07/18/2022, 3:09 PMfilter
should be fine. Especially that it's quite concise.Youssef Shoaib [MOD]
07/18/2022, 5:11 PMval indexOfRemoveMe = oldList.indexOfFirst { it.id == removeMe.id }
val newList = buildList(oldList.size) {
addAll(oldList)
if(indexOfRemoveMe >= 0) removeAt(removeMe)
}
Klitos Kyriacou
07/18/2022, 5:19 PMYoussef Shoaib [MOD]
07/18/2022, 5:23 PMLukasz Kalnik
07/18/2022, 5:27 PMJoffrey
07/18/2022, 5:28 PMremoveAt
in an array list would shift all following items to the left and be incredibly inefficient (at least compared to just initializing to the right size and copying items except the one at the given index). That is probably even worse than the filter
approach, actually.Youssef Shoaib [MOD]
07/18/2022, 5:30 PMremoveAt
Joffrey
07/18/2022, 5:33 PMI considered also to addAll the elements before and addAll the elements after, but that, I think, is as performant as aI don't think so, it would just do 2 arraycopy for the 2 ranges, instead of copying everything + re-copying the second part. But I agree that this would be better than aremoveAt
filter
that uses an iterator and adds each element one by one.Youssef Shoaib [MOD]
07/18/2022, 5:38 PMtoArray
on the collection) and so removeAt
would create one array instead of 2 and then resize within that array. I honestly didn't know if the extra array was worse or not though.ephemient
07/18/2022, 5:45 PMJoffrey
07/18/2022, 5:56 PMKlitos Kyriacou
07/18/2022, 8:04 PMfilterTo
for when you know the target size.