How to reverse a list in scala
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 listsimportscala.collection.immutable._// Creating objectobjectGFG{// Main methoddefmain(args:Array[String]){// Creating and initializing immutable listsvalmylist:List[String]=List("Geeks","For","geeks","is","best")// Display the value of mylist1println("Reversed List is: "+ mylist.reverse)}}chevron_rightfilter_noneOutput:
Reversed List is: List(best, is, geeks, For, Geeks)
- Reverse a list using for loop
// Scala program to print reverse immutable lists// using for loopimportscala.collection.immutable._// Creating objectobjectGFG{// Main methoddefmain(args:Array[String]){// Creating and initializing immutable listsvalmylist:List[String]=List("Geeks","For","geeks","is","a","fabulous","portal")// Display the value of mylist in// reverse order using for loopfor(element<-mylist.reverse){println(element)}}}chevron_rightfilter_noneOutput:
portal fabulous a is geeks For Geeks
- Reverse a list using foreach loop
// Scala program to reverse a list// using foreach loopimportscala.collection.immutable._// Creating objectobjectGFG{// Main methoddefmain(args:Array[String]){// Creating and initializing immutable listsvalmylist=List("Geeks","For","geeks","is","a","fabulous","portal")print("Original list is: ")// Display the value of mylist using for loopmylist.foreach{x:String=>print(x +" ") }// calling reverse functionprintln("\nReversed list: "+ mylist.reverse)}}chevron_rightfilter_noneOutput:
Original list is: Geeks For geeks is a fabulous portal Reversed list: List(portal, fabulous, a, is, geeks, For, Geeks)
Recommended Posts:
- How to Reverse keys and values in Scala Map
- Scala List max() method with example
- Scala List take() method with example
- Scala List :::() operator with example
- How to get the first element of List in Scala
- Scala List ::() operator with example
- Scala List +() operator with example
- Scala List map() method with example
- Scala List sum() method with example
- Scala List concatenation with example
- Scala List contains() method with example
- Scala List min() method with example
- How to print a list in Scala
- Scala List takeWhile() method with example
- Scala List product() method with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



