Open In App

How to reverse a list in scala

Last Updated : 17 Apr, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
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
    // 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
    // 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
    // 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)

Next Article
Article Tags :

Similar Reads