10.18. Extracting a Sequence of Elements from a Collection
Problem
You want to extract a sequence of contiguous elements from a collection, either by specifying a starting position and length, or a function.
Solution
There are quite a few collection methods you can use to extract a
contiguous list of elements from a sequence, including drop
, dropWhile
, head
, headOption
, init
, last
,
lastOption
, slice
, tail
, take
,
takeWhile
.
Given the following Array
:
scala> val x = (1 to 10).toArray
x: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
The drop
method drops the
number of elements you specify from the beginning of the
sequence:
scala> val y = x.drop(3)
y: Array[Int] = Array(4, 5, 6, 7, 8, 9, 10)
The dropWhile
method drops
elements as long as the predicate you supply returns true
:
scala> val y = x.dropWhile(_ < 6)
y: List[Int] = List(6, 7, 8, 9, 10)
The dropRight
method works like
drop
, but starts at the end of the
collection and works forward, dropping elements from the end of the
sequence:
scala> val y = x.dropRight(4)
y: Array[Int] = Array(1, 2, 3, 4, 5, 6)
take
extracts the first N
elements from the sequence:
scala> val y = x.take(3)
y: Array[Int] = Array(1, 2, 3)
takeWhile
returns elements as
long as the predicate you supply returns true
:
scala> val y = x.takeWhile(_ < 5)
y: Array[Int] = Array(1, 2, 3, 4)
takeRight
works the same way
take
works, but starts at the end of
the sequence and moves forward, taking the specified number of elements
from the end of the sequence:
scala> val y = x.takeRight(3) ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.