object SeqTransformation {
def main(args: Array[String]): Unit = {
val seq = Seq(1, 2, 3, 4, 5)
// Applies a function to each element.
val doubled = seq.map(_ * 2)
println(doubled)
// Applies a function that returns a collection and flattens the result.
// Expand each element into multiple elements
val flatMapped = seq.flatMap(x => Seq(x, x * 2))
println(flatMapped)
// Filters elements based on a predicate.
val filtered = seq.filter(_ % 2 == 0)
println(filtered)
// Chaining transformations
val processed: Seq[Int] = seq
.filter(_ > 3) // keep numbers greater than 3
.map(_ * 100) // multiply each by 100
.sorted // sort ascending
println(processed)
// Using for-comprehension
val comprehensionResult: Seq[String] = for {
n <- seq if n % 2 != 0 // odd numbers only
} yield s"Odd-$n"
println(comprehensionResult)
}
}
/*
run:
List(2, 4, 6, 8, 10)
List(1, 2, 2, 4, 3, 6, 4, 8, 5, 10)
List(2, 4)
List(400, 500)
List(Odd-1, Odd-3, Odd-5)
*/