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")
Share:
59,475
Govind Singh
Author by

Govind Singh

Making stuff work... most of the time.

Updated on July 31, 2020

Comments

  • Govind Singh
    Govind Singh almost 4 years

    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.

  • MaxG
    MaxG almost 6 years
    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.
  • Chris Martin
    Chris Martin almost 6 years
    @MaxG No, because drop on a linked list doesn't involve any copying.
  • Xavier Guihot
    Xavier Guihot over 5 years
    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