Scala Common Collection Operations

By: Stephen Patrick | 14 Aug 2016 | Category: Scala Language Basics

Scala Common Collection Operations

We will look at some common operations performed on Scala collections.

Scala Transform A Collection

In Scala the map method can be used to transform a collection. The map method applies a function to every method on a collection, returning a new collection of a similar type.

var intList = List(1,2,3)
def square= (x:Int) => x * x


List[Int] = List(1, 4, 9)

Above we pass a function square to the map function. The function returns a new List with all of the elements squared.

Scala Sum Elements Of A List

To sum the elements of a list the foldLeft method can be used. The foldLeft element maintains state
through the use of a variable while iterating through every element of the collection.

var intList = List(1,2,3)
intList.foldLeft(0) { (sum,element) =>
   sum+ element


Int = 6

Scala Pattern Matching

When working with Maps we sometimes need to make a decision on a certain action to take for a given return value. We can use pattern matching to process a returned Option value. This allows us to easily handle the return value without having to worry if an exception was thrown. We can use pattern matching to follow a path of execution based on the type of a value.

val char = alphaMap.get(3)

val result = char match {
   case None => "Char Not Found"
   case Some(value) => "Found "+value+""


String = Char Not Found

Scala Transform A Collection Into A Map

The groupBy method can be used to transform a collection into a Map.

class Field(val name:String, val fieldType:String)
var fieldList = List(new Field("name", "String"),  new Field("amount", "Double"))
var fieldMap = fieldList.groupBy(