0Pricing
Scala for Backend Engineering & Functional Programming · Aula

Transformações e ações

Computação preguiçosa.

Transformações e ações é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Two Kinds of Operations

Spark operations split into transformations (build a new dataset, lazy) and actions (trigger computation and return a result or write output).

Lazy Evaluation

Transformations are lazy: they record what to do but run nothing. Spark builds a directed acyclic graph (DAG) of transformations and only executes when an action is called.

map and filter

map transforms each element; filter keeps elements matching a predicate. Both return new RDDs/Datasets and do not run yet.

val nums  = sc.parallelize(1 to 10)
val evens = nums.filter(_ % 2 == 0).map(_ * 10)
// nothing computed yet

flatMap

flatMap maps each element to zero or more outputs and flattens them — classic for splitting lines into words.

val lines = sc.parallelize(Seq("hello world", "spark rocks"))
val words = lines.flatMap(_.split(" "))

Common Actions

Actions trigger execution:

  • collect — bring all results to the driver
  • count — number of elements
  • first / take(n) — sample rows
  • reduce — fold into one value
val total = sc.parallelize(1 to 100).reduce(_ + _)
println(total) // 5050 — runs now

Narrow vs Wide

Narrow transformations (map, filter) need no data movement. Wide transformations (groupByKey, reduceByKey, join) trigger a shuffle across the network.

reduceByKey

On key-value RDDs, reduceByKey aggregates values per key. It combines locally before shuffling, making it more efficient than groupByKey.

val pairs  = sc.parallelize(Seq(("a", 1), ("b", 1), ("a", 1)))
val counts = pairs.reduceByKey(_ + _)
// (a, 2), (b, 1)

Caching

If a dataset is reused across multiple actions, cache or persist keeps it in memory so it is not recomputed each time.

val cached = sc.parallelize(1 to 1000).filter(_ % 3 == 0).cache()
println(cached.count())
println(cached.sum())

DataFrame Transformations

DataFrames have their own lazy transformations: select, where, withColumn, orderBy. Actions like show and collect trigger them.

import org.apache.spark.sql.functions._

val adults = df.where(col("age") >= 18)
               .withColumn("adult", lit(true))
adults.show()

The Word Count Classic

The canonical Spark job: split lines, map each word to one, reduce by key. Only the final collect runs the pipeline.

val text   = sc.textFile("book.txt")
val counts = text.flatMap(_.split(" "))
                 .map(w => (w, 1))
                 .reduceByKey(_ + _)
counts.collect().foreach(println)

Plain Scala Lazy Analog

A self-contained Scala analog: a lazy view defers work until forced, mirroring Spark's transformation/action split.

object Main {
  def main(args: Array[String]): Unit = {
    val pipeline = (1 to 10).view.filter(_ % 2 == 0).map(_ * 10) // lazy
    val result = pipeline.toList // forces evaluation (action)
    println(result)
  }
}

Quick Check

When does Spark actually execute a chain of map and filter transformations?

Recap

You learned Spark's execution model:

  • Transformations are lazy (map, filter, flatMap, reduceByKey)
  • Actions trigger work (collect, count, reduce)
  • narrow vs wide (shuffle) operations
  • cache to reuse results

Next: Spark SQL.

Perguntas Frequentes

A aula “Transformações e ações” é grátis?

Sim — o texto completo de “Transformações e ações” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.

O que vou aprender em “Transformações e ações”?

Computação preguiçosa. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?

Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Transformações e ações”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?

Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. RDDs e DataFrames
  2. Transformações e ações
  3. Spark SQL
  4. Agregações
← Voltar para Scala for Backend Engineering & Functional Programming