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("
Last element is: " + temp_list.last)    } }

Output

$scala HelloWorld
Hello, World, SCALA, is, awesome,
Last element is: awesome

Updated on: 20-Aug-2020

503 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements