×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

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

By IncludeHelp Last updated : November 14, 2024

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. Using 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.

Example

object MyClass {
    def main(args: Array[String]): Unit = {
        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. Using 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.

Example

object MyClass {
    def main(args: Array[String]): Unit = {
        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. Using headOption

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

Syntax

set_name.headOption

Example

object MyClass {    
    def main(args: Array[String]): Unit = {
        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.