Scala tip: How to extract a field from a sequence of objects to create a new sequence

As a brief Scala tip, a fun thing you can do with the map method on Scala sequences (Array, List, Seq, Vector, etc.) is to convert a sequence of objects into a sequence of something else, typically extracting a field from the original object to create the new sequence.

For instance, imagine that you have a case class named Person that has two constructor parameters, firstName and lastName:

case class Person(firstName: String, lastName: String)

Next, create an Array of sample people:

val people = Array(
    Person("wilma", "flintstone"), 
    Person("barney", "rubble")

Now you can use the map method on the people sequence to create a new sequence of just first names, i.e., a Seq[String]:

scala> val firstNames =
firstNames: Array[String] = Array(fred, wilma, barney)

While this is a simple example, that’s a pretty cool technique for extracting a field from a sequence of objects to a more simple sequence, in this case a sequence of String types.

A sequence of objects to a sequence of tuples

Of course you can do even more with this technique. In the following example I convert a Seq[Car] to a sequence of tuples, in this case resulting in a Seq[(String, String)]:

scala> case class Car(make: String, model: String, year: Int)
defined class Car

scala> val rav4 = Car("Toyota", "RAV-4", 2006)
rav4: Car = Car(Toyota,RAV-4,2006)

scala> val pt = Car("Chrysler", "PT-Cruiser", 2003)
pt: Car = Car(Chrysler,PT-Cruiser,2003)

scala> val sebring = Car("Chrysler", "Sebring Convertible", 2000)
sebring: Car = Car(Chrysler,Sebring Convertible,2000)

scala> val cars = Seq(rav4, pt, sebring)
cars: Seq[Car] = List(Car(Toyota,RAV-4,2006), Car(Chrysler,PT-Cruiser,2003), Car(Chrysler,Sebring Convertible,2000))

// convert the Seq[Car] to a Seq[(String, String)]
scala> => (c.make, c.model))
res0: Seq[(String, String)] = List((Toyota,RAV-4), (Chrysler,PT-Cruiser), (Chrysler,Sebring Convertible))

As you can see, this is a nice little technique to have in your toolbox.