Get first n elements from List

john smith picture john smith · Jul 25, 2014 · Viewed 30.1k times · Source

I have a List

val family=List("1","2","11","12","21","22","31","33","41","44","51","55")

i want to take its first n elements but the problem is that parents size is not fixed.

val familliar=List("1","2","11") //n=3

Answer

Ende Neu picture Ende Neu · Jul 25, 2014

You can use take

scala> val list = List(1,2,3,4,5,6,7,8,9)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> list.take(3)
res0: List[Int] = List(1, 2, 3)