Methods to “update” Scala Vector and Seq

This page shows a few examples of methods that can be used to “update” a Scala Vector. Note that these same methods will also work with a Scala Seq, including IndexedSeq.

How to “update” Vector elements

Because Vector is immutable, you can’t update elements in place, but depending on your definition of “update,” there are a variety of methods that let you update a Vector as you assign the result to a new variable:

Method Returns
collect(pf) A new collection by applying the partial function pf to all elements of the vector, returning elements for which the function is defined
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) Return a new sequence by applying the function f to each element in the Vector
updated(i,v) A new vector with the element at index i replaced with the new value v
union(s) A new vector that contains elements from the current vector and the sequence s
val x = Vector(Some(1), None, Some(3), None)

val y = x.collect{case Some(i) => i}     # Vector(1, 3)

val x = Vector(1,2,1,2)
val y = x.distinct                       # Vector(1, 2)
val y = x.map(_ * 2)                     # Vector(2, 4, 2, 4)
val y = x.updated(0,100)                 # Vector(100, 2, 1, 2)

val a = Vector(Seq(1,2), Seq(3,4))
val y = a.flatten                        # Vector(1, 2, 3, 4)

val fruits = Vector("apple", "pear")
val y = fruits.map(_.toUpperCase)        # Vector(APPLE, PEAR)
val y = fruits.flatMap(_.toUpperCase)    # Vector(A, P, P, L, E, P, E, A, R)

val y = Vector(2,4).union(Vector(1,3))   # Vector(2, 4, 1, 3)

More information

I created this tutorial to show examples of how to update a 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.