从List中获取前n个元素

joh*_*ith 21 collections scala list scala-collections

我有一个 List

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

我想采取它的前n个元素,但问题是parents大小不固定.

val familliar=List("1","2","11") //n=3
Run Code Online (Sandbox Code Playgroud)

End*_*Neu 24

您可以使用 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)
Run Code Online (Sandbox Code Playgroud)


Xia*_*ong 5

List(1,2,3).take(100) //List(1,2,3)
Run Code Online (Sandbox Code Playgroud)

take的签名会将参数与index进行比较,因此增量索引永远不会超过参数

采取的签名

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
}
Run Code Online (Sandbox Code Playgroud)