w3resource

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

Scala Programming List Exercise-10 with Solution

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

Scala Code Editor :

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

Previous: 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.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/list/scala-list-exercise-10.php