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
import scala.collection.immutable. _
object GFG
{
def main(args : Array[String])
{
val mylist : List[String] = List( "Geeks" , "For" ,
"geeks" , "is" , "best" )
println( "Reversed List is: " + mylist.reverse)
}
}
|
Output:
Reversed List is: List(best, is, geeks, For, Geeks)
- Reverse a list using for loop
import scala.collection.immutable. _
object GFG
{
def main(args : Array[String])
{
val mylist : List[String] = List( "Geeks" , "For" , "geeks" , "is" ,
"a" , "fabulous" , "portal" )
for (element < -mylist.reverse)
{
println(element)
}
}
}
|
Output:
portal
fabulous
a
is
geeks
For
Geeks
- Reverse a list using foreach loop
import scala.collection.immutable. _
object GFG
{
def main(args : Array[String])
{
val mylist = List( "Geeks" , "For" , "geeks" , "is" ,
"a" , "fabulous" , "portal" )
print( "Original list is: " )
mylist.foreach{x : String => print(x + " " ) }
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)
Last Updated :
17 Apr, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...