Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to create sequence transformation in Scala

1 Answer

0 votes
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)

*/

 



answered Nov 15, 2025 by avibootz
edited Nov 15, 2025 by avibootz
...