How to get the first element of list in Scala?

Here, we will learn to access that first element of the list in Scala with working code and examples.
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 first element of the list

The first element of the list can be easily accessed using one of the two ways listed below:

  1. By using the index value (0) of the first element
  2. By using the list.head method

Accessing the first element using the index value

We can easily access the first element of the list by using its index value. And the indexing of the list is similar to that of an array i.e. the indexing starts at 0.

So, the first element will be at 0 index in the list.

Syntax

listName(0)

Program to illustrate the working of our solution

object MyClass {
    def main(args: Array[String]) {
        val myList = List("Scala", "Python", "C/C++", "JavaScript")
        println("The list is : " + myList)
        println("The first element of the list is " + myList(0))
    }
}

Output

The list is : List(Scala, Python, C/C++, JavaScript)
The first element of the list is Scala

Accessing the first element of the list using the list.head method

There are many inbuilt methods to support the functioning of a data structure in Scala. List is not an exception to that; the first element can be accessed using the inbuilt function head.

Syntax

list.head

Program to illustrate the working of our solution

object MyClass {
    def main(args: Array[String]) {
        val myList = List('a', 'g', 'i', 'h', 's', 'z')
        println("The list is : " + myList)
        println("The first element of the list is " + myList.head)
    }
}

Output

The list is : List(a, g, i, h, s, z)
The first element of the list is a

Scala List Programs »





Comments and Discussions!

Load comments ↻





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