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

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.