How to remove an item from a list in Scala having only its index?
If you insist on using the oldschool method, use collect:
List(1,2,3,4).zipWithIndex.collect { case (a, i) if i != 2 => a }
However, I still prefer the method in my other answer.
Simply use
val trunced = internalIdList.take(index) ++ internalIdList.drop(index + 1)
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:
scala> List(11,12,13,14,15).zipWithIndex.filter(_._2 != 2).map(_._1)
res0: List[Int] = List(11, 12, 14, 15)
But you can also use splitAt
:
scala> val (x,y) = List(11,12,13,14,15).splitAt(2)
x: List[Int] = List(11, 12)
y: List[Int] = List(13, 14, 15)
scala> x ++ y.tail
res5: List[Int] = List(11, 12, 14, 15)
There is a .patch
method on Seq
, so in order to remove the third element you could simply do this:
List(11, 12, 13, 14, 15).patch(2, Nil, 1)
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.