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.

Community
  • 1
  • 1
Govind Singh
  • 15,282
  • 14
  • 72
  • 106

2 Answers2

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
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • 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 '18 at 20:51
  • 1
    @MaxG No, because `drop` on a linked list doesn't involve any copying. – Chris Martin Jul 29 '18 at 15:24
  • 2
    Note that if your `Iterable` has at least 2 elements, you could use [`init`](https://www.scala-lang.org/api/current/scala/collection/Iterable.html#init:Repr) and [`tail`](https://www.scala-lang.org/api/current/scala/collection/Iterable.html#tail:Repr) to select respectively all elements except the last and all elements except the first: `List("one", "two", "three", "four").init.tail` – Xavier Guihot Jan 18 '19 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")
Kigyo
  • 5,668
  • 1
  • 20
  • 24