w3resource

Scala Programming: Reverse a given list


Write a Scala program to reverse a given list.

Sample Solution:

Scala Code:

object Scala_List {  
  
    
   def main(args: Array[String]): Unit = {
     val nums = List(1,2,3,4,5,6,7,8,9,10)
     println("Original List")
     println(nums)
     println("Reversed the said list:")
     println("Using reverse() function:")
     println(nums.reverse)
     println("Using for loop:")
     for(n<-nums.reverse)  
        {  
          print(n)  
          print(" ")
        }  
     }
}

Sample Output:

Original List
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Reversed the said list:
Using reverse() function:
List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Using for loop:
10 9 8 7 6 5 4 3 2 1 

Go to:


PREV : Write a Scala program to find an element from the last position of a given list.
NEXT : Write a Scala program to check a given list is a palindrome or not.

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.