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

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





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.