I have a list as follows:
val internalIdList: List[Int] = List()
internalIdList = List(11, 12, 13, 14, 15)
From this list would remove the third element in order to obtain:
internalIdList = List(11, 12, 14, 15)
I can not use a ListBuffer
, are obliged to maintain the existing structure.
How can I do?
Thanks to all
Simply use
This will also work if index is larger than the size of the list (It will return the same list).
An idiomatic way to do it is to zip the value with their index, filter, and then project the value again:
But you can also use
splitAt
:There is a
.patch
method onSeq
, so in order to remove the third element you could simply do this:Which says: Starting at index 2, please remove 1 element, and replace it with Nil.
Knowing this method in depth enables you to do so much more than that. You can swap out any sublist of a list with arbitrary other.
To generalise this...
Although this will often return a Vector, so you would need to do
If you really wanted a list back.
Shadowlands has a solution which tends to be faster for linear sequences. This one will be faster with indexed sequences.
A generic function that implements Nicolas' first solution:
Usage:
Using a for comprehension on a list
xs
like this,Also consider a set of exclusion indices, for instance
val excl = Set(2,4)
for excluding the second and fourth items; hence we collect those items whose indices do not belong to the exclusion set, namely