0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Functional Operations on Collections

Master common functional operations such as map, filter, fold, and reduce for data transformation.

Functional Operations on Collections is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Functional Ops: Why Use Them?

Functional operations on collections help you transform and combine data without changing the original collection. This approach promotes immutability and makes your code easier to read and test.

We'll explore key operations like map, filter, reduce, and fold.

Transform with `map`

The map operation applies a function to each element of a collection and returns a new collection with the transformed results. The original collection remains unchanged.

Try running this example:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4)
    val doubled = numbers.map(n => n * 2)
    println(s"Original: $numbers")
    println(s"Doubled: $doubled")
  }
}

`map` with Different Types

map is very flexible! You can transform elements into a completely different type. Here, we convert numbers to strings, or get string lengths.

Notice how the result is a List[Int], even though the input was List[String].

object Main {
  def main(args: Array[String]): Unit = {
    val names = List("Alice", "Bob", "Charlie")
    val lengths = names.map(name => name.length)
    println(s"Names: $names")
    println(s"Lengths: $lengths")
  }
}

Select with `filter`

The filter operation creates a new collection containing only the elements that satisfy a given condition (a predicate function). It "filters out" unwanted elements.

Let's find the even numbers:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4, 5, 6)
    val evens = numbers.filter(n => n % 2 == 0)
    println(s"Original: $numbers")
    println(s"Evens: $evens")
  }
}

More `filter` Examples

You can use any boolean expression as your filter condition. Let's filter a list of words to keep only those longer than 4 characters.

object Main {
  def main(args: Array[String]): Unit = {
    val words = List("apple", "cat", "banana", "dog", "elephant")
    val longWords = words.filter(w => w.length > 4)
    println(s"Words: $words")
    println(s"Long words: $longWords")
  }
}

Combine with `reduce`

The reduce operation combines all elements of a collection into a single result. It takes a binary operation (a function that takes two arguments and returns one) and applies it cumulatively.

Here, we sum all elements:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4)
    val sum = numbers.reduce((a, b) => a + b)
    println(s"Numbers: $numbers")
    println(s"Sum: $sum")
  }
}

`reduce` for Product & Max

reduce can perform various aggregations. We can calculate the product of numbers or find the maximum value.

Note: reduce will throw an error on an empty collection.

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 5, 2, 8)
    val product = numbers.reduce((a, b) => a * b)
    val maxNum = numbers.reduce((a, b) => if (a > b) a else b)
    println(s"Numbers: $numbers")
    println(s"Product: $product")
    println(s"Max: $maxNum")
  }
}

`fold`: Initial Value Power

fold is similar to reduce but with an important difference: it takes an initial value (also called an "accumulator"). This makes it safe for empty collections and allows for different result types.

Let's sum numbers, starting from 10:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3)
    // foldLeft(initialValue)(operation)
    val sumWithInitial = numbers.foldLeft(10)((acc, n) => acc + n)
    println(s"Numbers: $numbers")
    println(s"Sum (starting from 10): $sumWithInitial")
  }
}

Direction: `foldLeft` vs `foldRight`

Scala offers foldLeft and foldRight. They differ in the order of processing elements and how the accumulator is passed.

  • foldLeft(initial)(op): Processes left-to-right.
  • foldRight(initial)(op): Processes right-to-left.

For operations like string concatenation, the direction matters!

object Main {
  def main(args: Array[String]): Unit = {
    val chars = List('a', 'b', 'c')
    val leftFold = chars.foldLeft("")((acc, c) => acc + c)
    val rightFold = chars.foldRight("")((c, acc) => acc + c)
    println(s"Chars: $chars")
    println(s"foldLeft: $leftFold") // Output: abc
    println(s"foldRight: $rightFold") // Output: abc (due to string append order)

    // Example where order matters: (acc, char) => char + acc
    val rightFoldReversed = chars.foldRight("")((c, acc) => c + acc)
    println(s"foldRight (char + acc): $rightFoldReversed") // Output: abc

    // A common example where order matters is for operations like subtraction or division, but string concatenation also shows it.
  }
}

Functional Operations Check

Consider the following Scala code snippet:

val data = List(10, 20, 30, 40)
val result1 = data.map(x => x / 10)
val result2 = data.filter(x => x > 25)
val result3 = data.reduce((a, b) => a + b)

Which of the following statements are TRUE about the results?

Recap: Power of Functional Ops

You've mastered essential functional operations!

  • map transforms each element.
  • filter selects elements based on a condition.
  • reduce combines elements into a single result (requires non-empty collection).
  • fold combines elements with an initial value (safe for empty collections).

These operations are key for writing concise, immutable, and powerful Scala code. Next, we'll explore robust error handling using Option, Try, and Either.

Frequently asked questions

Is the “Functional Operations on Collections” lesson free?

Yes — the full text of “Functional Operations on Collections” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.

What will I learn in “Functional Operations on Collections”?

Master common functional operations such as map, filter, fold, and reduce for data transformation. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Functional Operations on Collections” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Immutable Collections Deep Dive
  2. Functional Operations on Collections
  3. Option, Try, Either for Errors
← Back to Scala for Backend Engineering & Functional Programming