第十章 Scala 容器基礎(十八):從集合中提取元素序列

Problem

    你想要從集合中提取一串連續的元素,經過指定開始和結束位置或者經過一個方法。
es6

Solution

    你能夠利用一些集合方法來從有序集合中提取一串連續的元素。好比drop,dropWhile,head,headOption,init,last,lastOption,slice,tail,take,takeWhile。
es5

    給定一個有序集合:scala

scala> val x = (1 to 10).toArray
x: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    利用drop(n)方法,你能夠提取集合除了前n個元素外,剩餘的元素。code

scala> x.drop(3)
res0: Array[Int] = Array(4, 5, 6, 7, 8, 9, 10)

    利用dropWhile方法,會丟掉從集合開始一直到能知足你傳給dropWhile方法的判斷條件爲true的全部元素。it

scala> x.dropWhile(_ < 6)
res2: Array[Int] = Array(6, 7, 8, 9, 10)

    dropRight(n)方法和drop很像,只不過它會丟掉集合右側的n個元素。io

scala> x.dropRight(3)
res4: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7)

    take(n)方法直接提取集合的前n個元素:ast

scala> x.take(4)
res5: Array[Int] = Array(1, 2, 3, 4)

    takeWhile(p)方法提取從集合開始直到第一個不知足p的元素以前的元素:class

scala> x.takeWhile(_ < 5)
res6: Array[Int] = Array(1, 2, 3, 4)

    takeRight(n)方法提取有序集合從後向前的n個元素:es7

scala> x.takeRight(3)
res7: Array[Int] = Array(8, 9, 10)

    slice(m,n)方法,會提取集合中第m個元素一直到第n-1個元素:List

scala> val peeps = List("John", "Mary", "Jane", "Fred")
peeps: List[String] = List(John, Mary, Jane, Fred)

scala> peeps.slice(1,3)
res9: List[String] = List(Mary, Jane)
Even more methods

    還有好多方法能夠返回集合的部分連續元素,其中init和tail能夠特別說一下,init返回集合除了最後一個元素以外的其餘元素,tail返回出了

scala> val nums = (1 to 5).toArray
nums: Array[Int] = Array(1, 2, 3, 4, 5)

scala> nums.head
res10: Int = 1

scala> nums.headOption
res11: Option[Int] = Some(1)

scala> nums.init
res12: Array[Int] = Array(1, 2, 3, 4)

scala> nums.last
res13: Int = 5

scala> nums.lastOption
res16: Option[Int] = Some(5)

scala> nums.tail
res17: Array[Int] = Array(2, 3, 4, 5)

scala> nums.init
res18: Array[Int] = Array(1, 2, 3, 4)
相關文章
相關標籤/搜索