By Alvin Alexander. Last updated: January 6, 2020
This page shows a few examples of “grouping” methods that can be used on the Scala Vector. Note that these same methods will also work with a Scala Seq
, including IndexedSeq
.
Grouping methods
Method | Returns |
---|---|
groupBy(f) |
A map of collections created by the function f |
grouped |
Breaks the vector into fixed-size iterable collections |
partition(p) |
Two collections created by the predicate p |
sliding(i,s) |
Group elements into fixed size blocks by passing a sliding window of size i and step s over them |
span(p) |
A collection of two collections; the first created by vector.takeWhile(p) , and the second created by vector.dropWhile(p) |
splitAt(i) |
A collection of two collections by splitting the vector at index i |
unzip |
The opposite of zip , breaks a collection into two collections by dividing each element into two pieces; such as breaking up a vector of Tuple2 elements |
Examples
val firstTen = (1 to 10).toVector # Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
firstTen.groupBy(_ > 5) # Map(false -> Vector(1, 2, 3, 4, 5), true -> Vector(6, 7, 8, 9, 10))
firstTen.grouped(2) # Iterator[Vector[Int]] = non-empty iterator
firstTen.grouped(2).toVector # Vector(Vector(1, 2), Vector(3, 4), Vector(5, 6), Vector(7, 8), Vector(9, 10))
firstTen.grouped(5).toVector # Vector(Vector(1, 2, 3, 4, 5), Vector(6, 7, 8, 9, 10))
"foo bar baz".partition(_ < 'c') # (" ba ba", foorz) // a Tuple2
firstTen.partition(_ > 5) # (Vector(6, 7, 8, 9, 10), Vector(1, 2, 3, 4, 5))
firstTen.sliding(2) # Iterator[Vector[Int]] = non-empty iterator
firstTen.sliding(2).toVector # Vector(Vector(1, 2), Vector(2, 3), Vector(3, 4), Vector(4, 5), Vector(5, 6), Vector(6, 7), Vector(7, 8), Vector(8, 9), Vector(9, 10))
firstTen.sliding(2,2).toVector # Vector(Vector(1, 2), Vector(3, 4), Vector(5, 6), Vector(7, 8), Vector(9, 10))
firstTen.sliding(2,3).toVector # Vector(Vector(1, 2), Vector(4, 5), Vector(7, 8), Vector(10))
firstTen.sliding(2,4).toVector # Vector(Vector(1, 2), Vector(5, 6), Vector(9, 10))
val x = Vector(15, 10, 5, 8, 20, 12)
x.groupBy(_ > 10) # Map(false -> Vector(10, 5, 8), true -> Vector(15, 20, 12))
x.partition(_ > 10) # (Vector(15, 20, 12), Vector(10, 5, 8))
x.span(_ < 20) # (Vector(15, 10, 5, 8), Vector(20, 12))
x.splitAt(2) # (Vector(15, 10), Vector(5, 8, 20, 12))
More information:
More on the Scala Vector
I created this tutorial to show examples of grouping methods on Scala Vector
or Seq
, but for many more examples of how to work with Vector
, see my Scala Vector class syntax and method examples tutorial.