0Pricing
Scala for Backend Engineering & Functional Programming · Lección

Operaciones funcionales sobre colecciones

Domine operaciones funcionales habituales, como map, filter, fold y reduce, para transformar datos.

Operaciones funcionales sobre colecciones es una lección gratuita de Scala for Backend Engineering & Functional Programming en CoddyKit. Esta es la lección 2 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Scala for Backend Engineering & Functional Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Scala for Backend Engineering & Functional Programming incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Operaciones funcionales sobre colecciones» es gratis?

Sí — el texto completo de «Operaciones funcionales sobre colecciones» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Scala for Backend Engineering & Functional Programming, actualiza a CoddyKit PRO. El curso de Scala for Backend Engineering & Functional Programming incluye 3 lecciones en total.

¿Qué aprenderé en «Operaciones funcionales sobre colecciones»?

Domine operaciones funcionales habituales, como map, filter, fold y reduce, para transformar datos. Practicas Scala for Backend Engineering & Functional Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Scala for Backend Engineering & Functional Programming?

No se requiere experiencia previa. Scala for Backend Engineering & Functional Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 3.

¿Cuánto tiempo toma la lección «Operaciones funcionales sobre colecciones»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Scala for Backend Engineering & Functional Programming?

Sí. Cada lección de Scala for Backend Engineering & Functional Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Profundización en colecciones inmutables
  2. Operaciones funcionales sobre colecciones
  3. Option, Try y Either para errores
← Volver a Scala for Backend Engineering & Functional Programming