How to reverse a list in Scala
1) Create a list for ex. 4,7,2,3.
Use var nums = List(4,7,2,3) to create the list.
2) To reverse this list type 'nums.reverse and choose reverese: List{Int}' from the auto-fill. Hit Run, you'll get the output as 3,2,4,7 as you can see in the picture below.
3) Also unlike java, it does not change the actual value of the "nums". It only gives the output in reverse without affecting the list "nums". As you can see below println function is still returning the original value of the "nums".
4) In a way, it is creating a new list same as giving the command:
var reverseNums = nums.reverse
5) So you can work with multiple threads in Scala, since it doesn't change the original variable.
Different methods to Reverse a List in Scala Example
Reverse Scala list (Simple Method)
import scala.collection.immutable._
object stechies // Create an object
{
def main(args:Array[String]) // Main method of program
{
val mylist: List[String] = List("Online", "Tutorials", "and", "free", "Training", "Materials", "on" ,"Stechies")
// Creating and initializing Scala List
println("Reversed List is: " + mylist.reverse)
// output
}
}
OUTPUT:
Reversed List is: List(Stechies, on, Materials, Training, free, and, Tutorials, Online)
Reverse a List in Scala using for loop Method
import scala.collection.immutable._
object stechies // Create an object
{
def main(args:Array[String]) // Main method of program
{
val mylist: List[String] = List("Online", "Tutorials", "and", "free", "Training", "Materials", "on" ,"Stechies")
// Creating and initializing Scala List
for(element<-mylist.reverse)
{
println(element)
// output
}
}
}
OUTPUT:
Stechies
on
Materials
Training
free
and
Tutorials
Online
Reverse List in Scala using Foreach Loop
import scala.collection.immutable._
object GFG // Create an object
{
def main(args:Array[String]) // Main method of program
{
val mylist: List[String] = List("Online", "Tutorials", "and", "free", "Training", "Materials", "on" ,"Stechies")
// Creating and initializing Scala List
print("Original list is: ")
// Display the current value of mylist using for loop
mylist.foreach{x:String => print(x + " ") }
// Reversing the List
println("nReversed list: " + mylist.reverse)
}
}
OUTPUT:
Original list is: Online Tutorials and free Training Materials on Stechies
Reversed list: List(Stechies, on, Materials, Training, free, and, Tutorials, Online)