Q:

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

belongs to collection: Scala List Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Program to convert Java List of floats to an Index... >>
<< How to get the first element of list in Scala?...