Scala program to find the last element in a list

1. Introduction

Finding the last element in a list is a common operation in many programming scenarios. Scala, being a functional language, offers a variety of ways to retrieve the last element from a list. This blog post will demonstrate how to find the last element in a list using Scala's standard library functions.

2. Program Steps

1. Initialize the Scala environment.

2. Define a sample list.

3. Use the last method provided by the List collection to retrieve the last element.

4. Print the last element.

5. Execute the program.

3. Code Program

object LastElementFinder {
  def main(args: Array[String]): Unit = {
    // Define a sample list
    val numbers = List(1, 2, 3, 4, 5)

    // Find the last element using the last method
    val lastElement = numbers.last

    println(s"List: $numbers")
    println(s"Last Element: $lastElement")
  }
}

Output:

List: List(1, 2, 3, 4, 5)
Last Element: 5

Explanation:

1. The entire program is contained within the LastElementFinder object.

2. A list called numbers is initialized with integer values.

3. To find the last element of the numbers list, we use the last method, which is a built-in function in Scala for lists.

4. The retrieved last element is printed to the console.

5. As seen in the output, for the list List(1, 2, 3, 4, 5), the last element is 5.


Comments