第十章 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)
相关文章
相关标签/搜索