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

Problem

    你想要从集合中提取一串连续的元素,通过指定开始和结束位置或者通过一个方法。

Solution

    你可以利用一些集合方法来从有序集合中提取一串连续的元素。比如drop,dropWhile,head,headOption,init,last,lastOption,slice,tail,take,takeWhile。

    给定一个有序集合:

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

    利用drop(n)方法,你可以提取集合除了前n个元素外,剩余的元素。

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

    利用dropWhile方法,会丢掉从集合开始一直到能满足你传给dropWhile方法的判断条件为true的所有元素。

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

    dropRight(n)方法和drop很像,只不过它会丢掉集合右侧的n个元素。

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

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

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

    takeWhile(p)方法提取从集合开始直到第一个不满足p的元素之前的元素:

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

    takeRight(n)方法提取有序集合从后向前的n个元素:

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

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

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)


转载于:https://my.oschina.net/nenusoul/blog/659530

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值