w3resource

Scala Programming: Find the first and last element of given list


Write a Scala program to find the first and last element of given list.

Sample Solution:

Scala Code:

object Scala_List
{
  def main(args: Array[String]): Unit = 
 {
   val colors = List("Red", "Blue", " Black ", "Green", " White", "Pink")
   println("Original list:")
   println(colors)  
   println("First element of the said list: " + colors.head) 
   println("Last element of the said list: " + colors.last)    
  }
}

Sample Output:

Original list:
List(Red, Blue,  Black , Green,  White, Pink)
First element of the said list: Red
Last element of the said list: Pink

Go to:


PREV : Write a Scala program to get the difference between two given lists.
NEXT : Write a Scala program to find the index of an element in a given list.

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.