remove first and last Element from scala.collection.immutable.Iterable[String]
59,475
Solution 1
Use drop
to remove from the front and dropRight
to remove from the end.
def removeFirstAndLast[A](xs: Iterable[A]) = xs.drop(1).dropRight(1)
Example:
removeFirstAndLast(List("one", "two", "three", "four")) map println
Output:
two
three
Solution 2
Another way is to use slice
.
val os: Iterable[String] = Iterable("a","b","c","d")
val result = os.slice(1, os.size - 1) // Iterable("b","c")
Comments
-
Govind Singh almost 4 years
I am trying to convert my way of getting values from
Form
, but stuck some whereval os= for { m <- request.body.asFormUrlEncoded v <- m._2 } yield v
os
isscala.collection.immutable.Iterable[String]
and when i print it in consoleos map println
console
sedet impntc sun job 03AHJ_VutoHGVhGL70
i want to remove the first and last element from it.
-
MaxG almost 6 yearsalthough it looks good, isn't this answer problematic? It seems as if the list is being copied twice: 1.
drop(1)
copies the list without first element. 2.dropRight(1)
copies it without the last element. -
Chris Martin almost 6 years@MaxG No, because
drop
on a linked list doesn't involve any copying. -
Xavier Guihot over 5 years