Skip to content
Related Articles

Related Articles

Improve Article

How to reverse a list in scala

  • Last Updated : 17 Apr, 2019

In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. We use reverse function to reverse a list in Scala.
Below are the examples to reverse a list.

  • Reverse a simple list




    // Scala program to reverse a simple Immutable lists 
    import scala.collection.immutable._
      
    // Creating object 
    object GFG 
        // Main method 
        def main(args:Array[String]) 
        
            // Creating and initializing immutable lists 
            val mylist: List[String] = List("Geeks", "For",
                                    "geeks", "is", "best"
          
            // Display the value of mylist1 
            println("Reversed List is: " + mylist.reverse) 
          
        

    Output:

    Reversed List is: List(best, is, geeks, For, Geeks)

     

  • Reverse a list using for loop




    // Scala program to print reverse immutable lists 
    // using for loop
    import scala.collection.immutable._
      
    // Creating object 
    object GFG
        // Main method 
        def main(args:Array[String]) 
        
            // Creating and initializing immutable lists 
            val mylist: List[String] = List("Geeks", "For", "geeks", "is",
                                            "a", "fabulous", "portal")
      
            // Display the value of mylist in
            // reverse order using for loop 
            for(element<-mylist.reverse) 
            
                println(element) 
            
        

    Output:

    portal
    fabulous
    a
    is
    geeks
    For
    Geeks

     

  • Reverse a list using foreach loop




    // Scala program to reverse a list
    // using foreach loop
    import scala.collection.immutable._
      
    // Creating object 
    object GFG
        // Main method 
        def main(args:Array[String]) 
        
            // Creating and initializing immutable lists 
            val mylist = List("Geeks", "For", "geeks", "is",
                            "a", "fabulous", "portal")
              
            print("Original list is: ")
              
            // Display the value of mylist using for loop 
            mylist.foreach{x:String => print(x + " ") }
              
            // calling reverse function
            println("\nReversed list: " + mylist.reverse)
        

    Output:

    Original list is: Geeks For geeks is a fabulous portal 
    Reversed list: List(portal, fabulous, a, is, geeks, For, Geeks)



My Personal Notes arrow_drop_up
Recommended Articles
Page :