By Alvin Alexander. Last updated: January 6, 2020
This page contains a large collection of examples of how to use Scala Vector class transformer methods.
Transformer methods
A transformer method is a method that constructs a new collection from an existing collection.
| Method | Returns |
|---|---|
collect(pf) |
Creates a new collection by applying the partial function pf to all elements of the vector, returning elements for which the function is defined |
diff(c) |
The difference between this vector and the collection c |
distinct |
A new sequence with no duplicate elements |
flatten |
Transforms a list of lists into a single list |
flatMap(f) |
When working with sequences, it works like map followed by flatten |
map(f) |
A new sequence by applying the function f to each element in the Vector |
reverse |
A new sequence with the elements in reverse order |
sortWith(f) |
A new sequence with the elements sorted with the use of the function f |
updated(i,v) |
A new Vector with the element at index i replaced with the new value v |
union(c) |
A new sequence that contains all elements of the vector and the collection c |
zip(c) |
A collection of pairs by matching the vector with the elements of the collection c |
zipWithIndex |
A vector of each element contained in a tuple along with its index |
val x = Vector(Some(1), None, Some(3), None)
x.collect{case Some(i) => i} # Vector(1, 3)
# diff
val oneToFive = (1 to 5).toVector # val oneToFive = (1 to 5).toVector
val threeToSeven = (3 to 7).toVector # Vector(3, 4, 5, 6, 7)
oneToFive.diff(threeToSeven) # Vector(1, 2)
threeToSeven.diff(oneToFive) # Vector(6, 7)
Vector(1,2,1,2).distinct # Vector(1, 2)
val a = Vector(Seq(1,2), Seq(3,4))
a.flatten # Vector(1, 2, 3, 4)
# map, flatMap
val fruits = Vector("apple", "pear")
fruits.map(_.toUpperCase) # Vector(APPLE, PEAR)
fruits.flatMap(_.toUpperCase) # Vector(A, P, P, L, E, P, E, A, R)
Vector(1,2,3).reverse # Vector(3, 2, 1)
val nums = Vector(10, 5, 8, 1, 7)
nums.sorted # Vector(1, 5, 7, 8, 10)
nums.sortWith(_ < _) # Vector(1, 5, 7, 8, 10)
nums.sortWith(_ > _) # Vector(10, 8, 7, 5, 1)
Vector(1,2,3).updated(0,10) # Vector(10, 2, 3)
Vector(2,4).union(Vector(1,3)) # Vector(2, 4, 1, 3)
# zip
val women = Vector("Wilma", "Betty") # Vector(Wilma, Betty)
val men = Vector("Fred", "Barney") # Vector(Fred, Barney)
val couples = women.zip(men) # Vector((Wilma,Fred), (Betty,Barney))
val a = Vector.range('a', 'e') # Vector(a, b, c, d)
a.zipWithIndex # Vector((a,0), (b,1), (c,2), (d,3))
Scala Vector summary
I created this tutorial to show examples of Scala Vector transformer methods, but for many more examples of how to work with Vector, see my Scala Vector class syntax and method examples tutorial.

