简体   繁体   中英

Get first n elements from List

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

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)
List(1,2,3).take(100) //List(1,2,3)

The signature of take will compare the argument with index, so the incremental index will never more than argument

The signature of take

override def take(n: Int): List[A] = {
  val b = new ListBuffer[A]
  var i = 0
  var these = this
  while (!these.isEmpty && i < n) {
    i += 1
    b += these.head
    these = these.tail
  }
  if (these.isEmpty) this
  else b.toList
}

使用take

val familliar = family.take(3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM