scalabeginner

Collections Map Filter Fold Operations

Master Scala collections: map, flatMap, filter, fold, groupBy, partition, and zip operations.

scala
case class Employee(name: String, dept: String, salary: Double)

@main def run(): Unit =
  val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

  // map, filter, reduce
  val doubled = numbers.map(_ * 2)
  val evens = numbers.filter(_ % 2 == 0)
  val sum = numbers.reduce(_ + _)
  println(s"Doubled: $doubled")
  println(s"Evens: $evens")
  println(s"Sum: $sum")

  // foldLeft with accumulator
  val product = numbers.foldLeft(1)(_ * _)
  val csv = numbers.foldLeft("") { (acc, n) =>
    if acc.isEmpty then n.toString else s"$acc,$n"
  }
  println(s"Product: $product")
  println(s"CSV: $csv")

  // flatMap
  val nested = List(List(1, 2), List(3, 4), List(5, 6))
  println(s"Flat: ${nested.flatten}")
  println(s"FlatMap: ${nested.flatMap(_.map(_ * 10))}")

  // groupBy, partition
  val employees = List(
    Employee("Alice", "Eng", 120000),
    Employee("Bob", "Eng", 110000),
    Employee("Carol", "Sales", 95000),
    Employee("Dave", "Sales", 105000),
    Employee("Eve", "Eng", 130000)
  )

  val byDept = employees.groupBy(_.dept)
  byDept.foreach { (dept, emps) =>
    println(s"$dept: ${emps.map(_.name).mkString(", ")}")
  }

  val (highPaid, lowPaid) = employees.partition(_.salary > 100000)
  println(s"High: ${highPaid.map(_.name)}")
  println(s"Low: ${lowPaid.map(_.name)}")

  // zip, zipWithIndex
  val names = List("Alice", "Bob", "Carol")
  val scores = List(95, 87, 92)
  println(s"Zipped: ${names.zip(scores)}")
  println(s"Indexed: ${names.zipWithIndex}")

  // collect (partial function)
  val mixed: List[Any] = List(1, "hello", 2, "world", 3)
  val ints = mixed.collect { case i: Int => i * 10 }
  println(s"Collected ints: $ints")

  // sliding, grouped
  val windowed = numbers.sliding(3).map(_.sum).toList
  println(s"Sliding sum: $windowed")
  numbers.grouped(3).foreach(g => println(s"Group: $g"))

Use Cases

  • Data transformation and aggregation
  • Functional collection processing
  • Batch and windowed operations

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.