Scala Seq class: Method examples (map, filter, fold, reduce)

Summary: This page contains many examples of how to use the methods on the Scala Seq class, including map, filter, foldLeft, reduceLeft, and many more.

Important note about Seq, IndexedSeq, and LinearSeq

As an important note, I use Seq in the following examples to keep things simple, but in your code you should be more precise and use IndexedSeq or LinearSeq where appropriate. As the Seq class Scaladoc states:

Seq has two principal subtraits, IndexedSeq and LinearSeq, which give different guarantees for performance. An IndexedSeq provides fast random-access of elements and a fast length operation. A LinearSeq provides fast access only to the first element via head, but also has a fast tail operation.”

Also, please see the “Seq is not Vector” section at the end of this post, because as that name implies, Seq behaves differently than Vector in almost all of these examples.

Important note about the examples

Seq is immutable, so in all of the examples that follow you need to assign the result of the operation shown to a new variable, like this:

val x = nums.distinct

I generally don’t do that in the examples (to keep the examples smaller and easier to read).

Create a new Seq with initial elements

To create a new Seq with initial elements:

val nums = Seq(1, 2, 3)

case class Person(name: String)
val people = Seq(
    Person("Emily"),
    Person("Hannah"),
    Person("Mercedes")
)

When you need to be clear about what’s in the seq:

val x = Seq(1, 1.0, 1F)                # Seq[Double] = List(1.0, 1.0, 1.0)
val x: Seq[Number] = Seq(1, 1.0, 1F)   # Seq[Number] = List(1, 1.0, 1.0)

trait Animal
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal

// creates: Seq[Animal] = List(Dog(Rover), Cat(Felix))
val animalHouse: Seq[Animal] = Seq(
    Dog("Rover"),
    Cat("Felix")
)

If you ever need to create an empty seq:

val nums = Seq[Int]()

Remember the construction syntax is just syntactic sugar for apply:

val nums = Seq(1, 2, 3)          # List(1, 2, 3)
val nums = Seq.apply(1, 2, 3)    # List(1, 2, 3)

Create a new Seq by populating it

You can also create a new Seq that’s populated with initial elements using a Range:

# to, until
(1 to 5).toSeq                   # List(1, 2, 3, 4, 5)
(1 until 5).toSeq                # List(1, 2, 3, 4)

(1 to 10 by 2).toSeq             # List(1, 3, 5, 7, 9)
(1 until 10 by 2).toSeq          # List(1, 3, 5, 7, 9)
(1 to 10).by(2).toSeq            # List(1, 3, 5, 7, 9)

('d' to 'h').toSeq               # List(d, e, f, g, h)
('d' until 'h').toSeq            # List(d, e, f, g)

('a' to 'f').by(2).toSeq         # List(a, c, e)

# range method
Seq.range(1, 3)                  # List(1, 2)
Seq.range(1, 6, 2)               # List(1, 3, 5)

You can also use the fill and tabulate methods:

Seq.fill(3)("foo")               # List(foo, foo, foo)
Seq.tabulate(3)(n => n * n)      # List(0, 1, 4)
Seq.tabulate(4)(n => n * n)      # List(0, 1, 4, 9)

Another note about Seq, IndexedSeq, and LinearSeq

I’m currently using Scala 2.12.4, and notice that when I declare a collection to be a Seq, the Scala REPL really gives me a List:

scala> val nums = Seq(1, 2, 3)
nums: Seq[Int] = List(1, 2, 3)
                 ----

Notice that IndexedSeq gives you a Vector and LinearSeq gives you a List:

scala> import scala.collection._
import scala.collection._

scala> val nums = IndexedSeq(1, 2, 3)
nums: IndexedSeq[Int] = Vector(1, 2, 3)

scala> val nums = LinearSeq(1, 2, 3)
nums: scala.collection.LinearSeq[Int] = List(1, 2, 3)

How to add (append and prepend) elements to a Scala Seq

Because the Scala Seq is immutable, you can’t add elements to an existing Seq. The way you work with Seq is to modify the elements it contains as you assign the results to a new Seq.

Method Description Example
:+ append 1 item oldSeq :+ e
++ append N items oldSeq ++ newSeq
+: prepend 1 item e +: oldSeq
++: prepend N items newSeq ++: oldSeq

Seq append and prepend examples

These examples show how to use the append and prepend methods:

# append
val v1 = Seq(4,5,6)              # List(4, 5, 6)
val v2 = v1 :+ 7                 # List(4, 5, 6, 7)
val v3 = v2 ++ Seq(8,9)          # List(4, 5, 6, 7, 8, 9)

# prepend
val v4 = 3 +: v3                 # List(3, 4, 5, 6, 7, 8, 9)
val v5 = Seq(1,2) ++: v4         # List(1, 2, 3, 4, 5, 6, 7, 8, 9)

About the : character in the method names

Note that during these operations the : character is always next to the old (original) sequence. I use that as a way to remember these methods.

The correct technical way to think about this is that a Scala method name that ends with the : character is right-associative, meaning that the method comes from the variable on the right side of the expression. Therefore, with +: and ++:, these methods comes from the Seq that’s on the right of the method name.

Filtering methods (how to “remove” elements from an Seq)

A Seq is an immutable sequence, so you don’t remove elements from a Seq. Instead, you describe how to remove elements as you assign the results to a new collection. These methods let you “remove” elements during this process:

Method Description
distinct Return a new sequence with no duplicate elements
drop(n) Return all elements after the first n elements
dropRight(n) Return all elements except the last n elements
dropWhile(p) Drop the first sequence of elements that matches the predicate p
filter(p) Return all elements that match the predicate p
filterNot(p) Return all elements that do not match the predicate p
find(p) Return the first element that matches the predicate p
head Return the first element; can throw an exception if the Seq is empty
headOption Returns the first element as an Option
init All elements except the last one
intersect(s) Return the intersection of the seq and another sequence s
last The last element; can throw an exception if the Seq is empty
lastOption The last element as an Option
slice(f,u) A sequence of elements from index f (from) to index u (until)
tail All elements after the first element
take(n) The first n elements
takeRight(n) The last n elements
takeWhile(p) The first subset of elements that matches the predicate p

Examples

val a = Seq(10, 20, 30, 40, 10)       # List(10, 20, 30, 40, 10)
a.distinct                            # List(10, 20, 30, 40)
a.drop(2)                             # List(30, 40, 10)
a.dropRight(2)                        # List(10, 20, 30)
a.dropWhile(_ < 25)                   # List(30, 40, 10)
a.filter(_ < 25)                      # List(10, 20, 10)
a.filter(_ > 100)                     # List()
a.filterNot(_ < 25)                   # List(30, 40)
a.find(_ > 20)                        # Some(30)
a.head                                # 10
a.headOption                          # Some(10)
a.init                                # List(10, 20, 30, 40)
a.intersect(Seq(19,20,21))            # List(20)
a.last                                # 10
a.lastOption                          # Some(10)
a.slice(2,4)                          # List(30, 40)
a.tail                                # List(20, 30, 40, 10)
a.take(3)                             # List(10, 20, 30)
a.takeRight(2)                        # List(40, 10)
a.takeWhile(_ < 30)                   # List(10, 20)

As noted, head and last can throw exceptions:

scala> val a = Seq[Int]()
a: Seq[Int] = List()

scala> a.head
java.util.NoSuchElementException: head of empty list
  at scala.collection.immutable.Nil$.head(List.scala:428)
  at scala.collection.immutable.Nil$.head(List.scala:425)
  ... 28 elided

scala> a.last
java.util.NoSuchElementException
  at scala.collection.LinearSeqOptimized.last(LinearSeqOptimized.scala:146)
  at scala.collection.LinearSeqOptimized.last$(LinearSeqOptimized.scala:145)
  at scala.collection.immutable.List.last(List.scala:86)
  ... 28 elided

How to “update” Seq elements

Because Seq 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 Seq 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 seq, 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 Seq
updated(i,v) A new seq with the element at index i replaced with the new value v
union(s) A new seq that contains elements from the current seq and the sequence s
val x = Seq(Some(1), None, Some(3), None)

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

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

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

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

Seq(2,4).union(Seq(1,3))            # List(2, 4, 1, 3)

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 seq, returning elements for which the function is defined
diff(c) The difference between this seq 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 Seq
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 Seq with the element at index i replaced with the new value v
union(c) A new sequence that contains all elements of the seq and the collection c
zip(c) A collection of pairs by matching the seq with the elements of the collection c
zipWithIndex A seq of each element contained in a tuple along with its index
val x = Seq(Some(1), None, Some(3), None)

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

# diff
val oneToFive = (1 to 5).toSeq       # val oneToFive = (1 to 5).toSeq
val threeToSeven = (3 to 7).toSeq    # List(3, 4, 5, 6, 7)
oneToFive.diff(threeToSeven)         # List(1, 2)
threeToSeven.diff(oneToFive)         # List(6, 7)

Seq(1,2,1,2).distinct                # List(1, 2)

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

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

Seq(1,2,3).reverse                   # List(3, 2, 1)

val nums = Seq(10, 5, 8, 1, 7)
nums.sorted                          # List(1, 5, 7, 8, 10)
nums.sortWith(_ < _)                 # List(1, 5, 7, 8, 10)
nums.sortWith(_ > _)                 # List(10, 8, 7, 5, 1)

Seq(1,2,3).updated(0,10)             # List(10, 2, 3)
Seq(2,4).union(Seq(1,3))             # List(2, 4, 1, 3)

# zip
val women = Seq("Wilma", "Betty")    # List(Wilma, Betty)
val men = Seq("Fred", "Barney")      # List(Fred, Barney)
val couples = women.zip(men)         # List((Wilma,Fred), (Betty,Barney))

val a = Seq.range('a', 'e')          # List(a, b, c, d)
a.zipWithIndex                       # List((a,0), (b,1), (c,2), (d,3))

Informational and mathematical methods

Informational and mathematical methods let you obtain information about a collection and the contents of the collection.

Method Returns
contains(e) True if the seq contains the element e
containsSlice(s) True if the seq contains the sequence s
count(p) The number of elements in the seq for which the predicate is true
endsWith(s) True if the seq ends with the sequence s
exists(p) True if the predicate returns true for at least one element in the seq
find(p) The first element that matches the predicate p, returned as an Option
forall(p) True if the predicate p is true for all elements in the seq
hasDefiniteSize True if the seq has a finite size
indexOf(e) The index of the first occurrence of the element e in the seq
indexOf(e,i) The index of the first occurrence of the element e in the seq, searching only from the value of the start index i
indexOfSlice(s) The index of the first occurrence of the sequence s in the seq
indexOfSlice(s,i) The index of the first occurrence of the sequence s in the seq, searching only from the value of the start index i
indexWhere(p) The index of the first element where the predicate p returns true
indexWhere(p,i) The index of the first element where the predicate p returns true, searching only from the value of the start index i
isDefinedAt(i) True if the seq contains the index i
isEmpty True if the seq contains no elements
lastIndexOf(e) The index of the last occurrence of the element e in the seq
lastIndexOf(e,i) The index of the last occurrence of the element e in the seq, occurring before or at the index i
lastIndexOfSlice(s) The index of the last occurrence of the sequence s in the seq
lastIndexOfSlice(s,i) The index of the last occurrence of the sequence s in the seq, occurring before or at the index i
lastIndexWhere(p) The index of the first element where the predicate p returns true
lastIndexWhere(p,i) The index of the first element where the predicate p returns true, occurring before or at the index i
max The largest element in the seq
min The smallest element in the seq
nonEmpty True if the seq is not empty (i.e., if it contains 1 or more elements)
product The result of multiplying the elements in the collection
segmentLength(p,i) The length of the longest segment for which the predicate p is true, starting at the index i
size The number of elements in the seq
startsWith(s) True if the seq begins with the elements in the sequence s
startsWith(s,i) True if the seq has the sequence s starting at the index i
sum The sum of the elements in the seq
fold(s)(o) “Fold” the elements of the seq using the binary operator o, using an initial seed s (see also reduce)
foldLeft(s)(o) “Fold” the elements of the seq using the binary operator o, using an initial seed s, going from left to right (see also reduceLeft)
foldRight(s)(o) “Fold” the elements of the seq using the binary operator o, using an initial seed s, going from right to left (see also reduceRight)
reduce “Reduce” the elements of the seq using the binary operator o
reduceLeft “Reduce” the elements of the seq using the binary operator o, going from left to right
reduceRight “Reduce” the elements of the seq using the binary operator o, going from right to left

Examples

First, some sample data:

val evens = Seq(2, 4, 6)                   # List(2, 4, 6)
val odds = Seq(1, 3, 5)                    # List(1, 3, 5)
val fbb = "foo bar baz"                    # String = foo bar baz
val firstTen = (1 to 10).toSeq             # List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val fiveToFifteen = (5 to 15).toSeq        # List(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
val empty = Seq[Int]()                     # List[Int] = Seq()
val letters = ('a' to 'f').toSeq           # List(a, b, c, d, e, f)

The examples:

evens.contains(2)                          # true
firstTen.containsSlice(Seq(3,4,5))         # true
firstTen.count(_ % 2 == 0)                 # 5
firstTen.endsWith(Seq(9,10))               # true
firstTen.exists(_ > 10)                    # false
firstTen.find(_ > 2)                       # Some(3)
firstTen.forall(_ < 20)                    # true
firstTen.hasDefiniteSize                   # true
empty.hasDefiniteSize                      # true
letters.indexOf('b')                       # 1 (zero-based)
letters.indexOf('d', 2)                    # 3
letters.indexOf('d', 3)                    # 3
letters.indexOf('d', 4)                    # -1
letters.indexOfSlice(Seq('c','d'))         # 2
letters.indexOfSlice(Seq('c','d'),2)       # 2
letters.indexOfSlice(Seq('c','d'),3)       # -1
firstTen.indexWhere(_ == 3)                # 2
firstTen.indexWhere(_ == 3, 2)             # 2
firstTen.indexWhere(_ == 3, 5)             # -1
letters.isDefinedAt(1)                     # true
letters.isDefinedAt(20)                    # false
letters.isEmpty                            # false
empty.isEmpty                              # true

# lastIndex...
val fbb = "foo bar baz"
fbb.indexOf('a')                           # 5
fbb.lastIndexOf('a')                       # 9
fbb.lastIndexOf('a', 10)                   # 9
fbb.lastIndexOf('a', 9)                    # 9
fbb.lastIndexOf('a', 6)                    # 5
fbb.lastIndexOf('a', 5)                    # 5
fbb.lastIndexOf('a', 4)                    # -1

fbb.lastIndexOfSlice("ar")                 # 5
fbb.lastIndexOfSlice(Seq('a','r'))         # 5
fbb.lastIndexOfSlice(Seq('a','r'), 4)      # -1
fbb.lastIndexOfSlice(Seq('a','r'), 5)      # 5
fbb.lastIndexOfSlice(Seq('a','r'), 6)      # 5

fbb.lastIndexWhere(_ == 'a')               # 9
fbb.lastIndexWhere(_ == 'a', 4)            # -1
fbb.lastIndexWhere(_ == 'a', 5)            # 5
fbb.lastIndexWhere(_ == 'a', 6)            # 5
fbb.lastIndexWhere(_ == 'a', 8)            # 5
fbb.lastIndexWhere(_ == 'a', 9)            # 9

firstTen.max                               # 10
letters.max                                # f
firstTen.min                               # 1
letters.min                                # a
letters.nonEmpty                           # true
empty.nonEmpty                             # false
firstTen.product                           # 3628800
letters.size                               # 6

val x = Seq(1,2,9,1,1,1,1,4)
x.segmentLength(_ < 4, 0)                  # 2
x.segmentLength(_ < 4, 2)                  # 0
x.segmentLength(_ < 4, 3)                  # 4
x.segmentLength(_ < 4, 4)                  # 3

firstTen.startsWith(Seq(1,2))              # true
firstTen.startsWith(Seq(1,2), 0)           # true
firstTen.startsWith(Seq(1,2), 1)           # false
firstTen.sum                               # 55

firstTen.fold(100)(_ + _)                  # 155
firstTen.foldLeft(100)(_ + _)              # 155
firstTen.foldRight(100)(_ + _)             # 155
firstTen.reduce(_ + _)                     # 55
firstTen.reduceLeft(_ + _)                 # 55
firstTen.reduceRight(_ + _)                # 55

firstTen.fold(100)(_ - _)                  # 45
firstTen.foldLeft(100)(_ - _)              # 45
firstTen.foldRight(100)(_ - _)             # 95
firstTen.reduce(_ - _)                     # -53
firstTen.reduceLeft(_ - _)                 # -53
firstTen.reduceRight(_ - _)                # -5

More on fold and reduce

Grouping methods

“Grouping” methods generally let you create multiple groups from a collection.

Method Returns
groupBy(f) A map of collections created by the function f
grouped Breaks the seq 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 seq.takeWhile(p), and the second created by seq.dropWhile(p)
splitAt(i) A collection of two collections by splitting the seq 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 seq of Tuple2 elements

Examples

val firstTen = (1 to 10).toSeq       # Range = Range 1 to 10

firstTen.groupBy(_ > 5)              # IndexedSeq[Int]] = Map(false -> Vector(1,2,3,4,5), true -> Vector(6,7,8,9,10))
firstTen.grouped(2)                  # IndexedSeq[Int]] = non-empty iterator
firstTen.grouped(2).toSeq            # IndexedSeq[Int]] = Stream(Vector(1, 2), ?)
firstTen.grouped(5).toSeq            # IndexedSeq[Int]] = Stream(Vector(1, 2, 3, 4, 5), ?)

"foo bar baz".partition(_ < 'c')     # (" ba ba", foorz)  # a Tuple2
firstTen.partition(_ > 5)            # (IndexedSeq[Int], IndexedSeq[Int]) = (Vector(6,7,8,9,10), Vector(1,2,3,4,5))

firstTen.sliding(2)                  # IndexedSeq[Int]] = non-empty iterator
firstTen.sliding(2).toSeq            # IndexedSeq[Int]] = Stream(Vector(1, 2), ?)
firstTen.sliding(2,2).toSeq          # IndexedSeq[Int]] = Stream(Vector(1, 2), ?)
firstTen.sliding(2,3).toSeq          # IndexedSeq[Int]] = Stream(Vector(1, 2), ?)
firstTen.sliding(2,4).toSeq          # IndexedSeq[Int]] = Stream(Vector(1, 2), ?)

# notice the difference between toSeq and toVector:
firstTen.sliding(2,4).toSeq          # IndexedSeq[Int]] = Stream(Vector(1, 2), ?)
firstTen.sliding(2,4).toVector       # Vector[IndexedSeq[Int]] = Vector(Vector(1, 2), Vector(5, 6), Vector(9, 10))

val x = Seq(15, 10, 5, 8, 20, 12)
x.groupBy(_ > 10)                    # Map[Boolean,Seq[Int]] = Map(false -> List(10, 5, 8), true -> List(15, 20, 12))
x.partition(_ > 10)                  # (Seq[Int], Seq[Int]) = (List(15, 20, 12),List(10, 5, 8))
x.span(_ < 20)                       # (Seq[Int], Seq[Int]) = (List(15, 10, 5, 8),List(20, 12))
x.splitAt(2)                         # (Seq[Int], Seq[Int]) = (List(15, 10),List(5, 8, 20, 12))

More information:

Looping over a Seq with for and foreach

These examples show how to loop over a Seq with for and foreach:

val oneToFive = Seq(1, 2, 3, 4, 5)   # Seq[Int] = List(1, 2, 3, 4, 5)

for (i <- oneToFive) yield i         # Seq[Int] = List(1, 2, 3, 4, 5)
for (i <- oneToFive) yield i * 2     # Seq[Int] = List(2, 4, 6, 8, 10)
for (i <- oneToFive) yield i % 2     # Seq[Int] = List(1, 0, 1, 0, 1)

for {                                # Seq[Int] = List(3, 4, 5)
    i <- oneToFive
    if i > 2
} yield i

for {                                # Seq[Int] = List(6, 8, 10)
    i <- oneToFive
    if i > 2
} yield {
    # could be multiple lines here
    i * 2
}

# foreach (which i rarely use)
val oneToThree = Seq(1, 2, 3)
oneToThree.foreach(print)            # 123
for (i <- oneToThree) print(i)       # 123

A few things you can do with a Seq of Options

The Option type is used a lot in idiomatic Scala code, so here are some ways to work with a Vector that contains Options.

val x = Seq(Some(1), None, Some(3), None)   # Seq[Option[Int]] = List(Some(1), None, Some(3), None)

x.flatten                                   # Seq[Int] = List(1, 3)
x.collect{case Some(i) => i}                # Seq[Int] = List(1, 3)


# map, flatten, flatMap
import scala.util.Try
def toInt(s: String): Option[Int] = Try(Integer.parseInt(s)).toOption
val strings = Seq("1", "2", "foo", "3", "bar")

strings.map(toInt)                   # Seq[Option[Int]] = List(Some(1), Some(2), None, Some(3), None)
strings.map(toInt).flatten           # Seq[Int] = List(1, 2, 3)
strings.flatMap(toInt)               # Seq[Int] = List(1, 2, 3)

Seq is not Vector

If you read my Scala Vector class examples post, you may have noticed that the data types that result from using Seq are significantly different than what you get from using Vector. This is most obviously true when you see the examples here where using a Seq results in a List or a Stream, while all of the Vector examples generally end up with a Vector result.

Scala Seq summary

In summary, I hope these Seq examples are helpful. If I made a mistake, or you know another way to do something with an Seq I haven’t shown, leave a note in the Comments section.

I hope this content has been helpful.

All the best,
Al