Home » Scala language

How to get the first element from the Set in Scala?

In this tutorial on Set in Scala, we will learn how to get the first element from the set in Scala programming language?
Submitted by Shivang Yadav, on December 03, 2019

Scala Set

A set in Scala is a collection of unique elements i.e. duplicate elements are not allowed in the Set.

Example:

    Set(10, 3, 213, 56, 9, 82)

Accessing First Element of Set

In the Scala programming language, to access the first element of the Set, there are multiple methods defined that can accomplish the task easily.

1) take() method

The take() method in Scala is used to return the Set of elements up to the specified length from the given Set. So, passing 1 as a parameter to the take() method will return a set with the first element only.

Program:

object MyClass {
    def main(args: Array[String]) {
        val bike = Set("Pulsar 150" , "Thunderbird 350", "Ninja 300", "Harley Davidson street 750")
        printf("all my bikes are : ")
        println(bike)
        println("My first bike was "+bike.take(1))
    }
}

Output

all my bikes are : Set(Pulsar 150, Thunderbird 350, Ninja 300, Harley Davidson street 750)
My first bike was Set(Pulsar 150)

Here the output is correct i.e. we wanted the first element and we got in too. But in a program, we need to change this set to an element so that it can be used in the code. So, there are other methods too that will do this job for us.

2) head method

The head method in the Scala is defined to return the first element of the set which call the method.

Syntax:

    Set_name.take;

The method does not accept any parameter, it returns the first value of the set.

Program:

object MyClass {
    def main(args: Array[String]) {
        val bike = Set("Pulsar 150" , "Thunderbird 350", "Ninja 300", "Harley Davidson street 750")
        printf("all my bikes are : ")
        println(bike)
        println("My first bike was "+bike.head)
    }
}

Output

all my bikes are : Set(Pulsar 150, Thunderbird 350, Ninja 300, Harley Davidson street 750)
My first bike was Pulsar 150

3) headOption

The headOption in Scala is also used to return the first element of the set that calls it.

Syntax:

    set_name.headOption

Program:

object MyClass {    
    def main(args: Array[String]) {
        val bike = Set("Pulsar 150" , "Thunderbird 350", "Ninja 300", "Harley Davidson street 750")
        printf("all my bikes are : ")
        println(bike)
        println("My first bike was "+bike.headOption)
    }
}

Output

all my bikes are : Set(Pulsar 150, Thunderbird 350, Ninja 300, Harley Davidson street 750)
My first bike was Some(Pulsar 150)



Comments and Discussions!

Load comments ↻






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