Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find the last element of a list in scala
Suppose we have a list in Scala, this list is defined under scala.collection.immutable package. As we know, a list is a collection of same type elements which contains immutable (cannot be changed) data. We generally apply last function to show last element of a list.
Using last keyword
The following Scala code is showing how to print the last element stored in a list of Scala.
Example
import scala.collection.immutable._
object HelloWorld {
def main(args: Array[String]) {
val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome")
println("Elements of temp_list: " + temp_list.last)
}
}
Output
$scala HelloWorld Elements of temp_list: awesome
Using For Loop
The following Scala code is showing how to print the last element stored in a list of Scala using for loop.
Example
import scala.collection.immutable._
object HelloWorld {
def main(args: Array[String]) {
val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome")
for(element<-temp_list.last) {
print(element)
}
}
}
Output
$scala HelloWorld awesome
Using Foreach Loop
The following Scala code is showing how to print the elements using for-each loop and display the last element.
Example
import scala.collection.immutable._
object HelloWorld {
def main(args: Array[String]) {
val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome")
temp_list.foreach{x:String => print(x + ", ") }
println("\nLast element is: " + temp_list.last)
}
}
Output
$scala HelloWorld Hello, World, SCALA, is, awesome, Last element is: awesome
Advertisements
