42

I am trying to convert my way of getting values from Form, but stuck some where

val os= for {
  m <- request.body.asFormUrlEncoded
  v <- m._2
} yield v

os is scala.collection.immutable.Iterable[String] and when i print it in console

os map println

console

sedet impntc
sun
job
03AHJ_VutoHGVhGL70

i want to remove the first and last element from it.

2 Answers 2

72

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
3
  • although 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.
    – MaxG
    Jul 28, 2018 at 20:51
  • 1
    @MaxG No, because drop on a linked list doesn't involve any copying. Jul 29, 2018 at 15:24
  • 2
    Note that if your Iterable has at least 2 elements, you could use init and tail to select respectively all elements except the last and all elements except the first: List("one", "two", "three", "four").init.tail Jan 18, 2019 at 13:22
7

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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.