Q:

How to get the first element of 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 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

All Answers

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

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

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

total answers (1)

How to find the last element of a list in Scala?... >>
<< How to create a range of characters (Lists, Sequen...