How to find the last element of a list in Scala?

Here, we will learn how to find the last element of a list in Scala with syntax and example of the method used?
Submitted by Shivang Yadav, on October 09, 2020 [Last updated : March 11, 2023]

List in Scala is a collection that stores data in the form of a linked-list. The list is an immutable collection which means the elements of a list cannot be altered after the list is created. We can access elements of the array using the index of the element.

Accessing the last element

The last element of the array can be accessed by 2 methods.

  1. By using the length of the list.
  2. By using the last function.

Accessing the last element using the length of the list

We will use the index of the list to find the element. For this, we will find the length of the list and use (length-1) as index to access the last element.

Syntax

listName(listName.lenght - 1)

Example to find the last element using the length of the list

object MyClass {
    def main(args: Array[String]) {
        val list1 = List(4, 1, 7, 3, 9, 2, 10)
        println("The list is " + list1)
        println("The last element of the list is " + list1(list1.length - 1))
    }
}

Output

The list is List(4, 1, 7, 3, 9, 2, 10)
The last element of the list is 10

Accessing the last element using the length of the list

To find the last element of the array, we will use the last function.

Syntax

listName.last

Example to find the last element using the last function

object MyClass {
    def main(args: Array[String]) {
        val list1 = List(4, 1, 7, 3, 9, 2, 10)
        println("The list is " + list1)
        println("The last element of the list is " + list1.last)
    }
}

Output

The list is List(4, 1, 7, 3, 9, 2, 10)
The last element of the list is 10

Scala List Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.