How to get a set of elements in a list based on the index of an element in Scala?
I have one list and the other list contains the index I am interested in. For example,
val a=List("a","b","c","d")
val b=List(2,3)
Then I need to return a list with the value List ("b", "c"), since List (2,3) said I like to take the 2nd and 3rd elements from element "a". How to do it?
+3
Daniel Wu
source
to share
3 answers
val results = b.map(i => a(i - 1))
+4
Lee
source
to share
I like the order of my expressions in the code to reflect the order of evaluation, so I like to use the scalaz operator for this type |>
b.map(_ - 1 |> a)
This is especially true when you are used to writing bash scripts.
+2
samthebest
source
to share
Consider this method apply
, which checks (avoids) possible IndexOutOfBoundsException
,
implicit class FetchList[A](val in: List[A]) extends AnyVal {
def apply (idx: List[Int]) = for (i <- idx if i < in.size) yield in(i-1)
}
Thus,
a(b)
res: List[String] = List(b, c)
+1
elm
source
to share