Find head/first and tail element from Set in Scala

58 total views, 1 views today

Welcome to Scala series. In this tutorial, you will learn about How to Find head/first and tail element from Set in Scala.

Scala Set basics

Scala set is a collection that stores only unique values. It doesn’t allow duplicates. Set is Iterable and inherits all functionality of the iterable interface. Check out this detailed post on Scala Set for various Set operations.

Basically Set in Scala has two variants.

  • Immutable Set(Which is the default)
  • Mutable Set(we need to explicitly import mutable Set)

Immutable Set allows us to apply a function on Set but resulting in the creation of a new Set every time. It doesn’t allow us to change the source. On the other hand, the mutable Set allows modifying the source itself.

Let us now learn how to Find the head/first and tail element from Set in Scala. Scala has provided inbuilt head() and tail() operation on collections that help us to identify head and tail values in the collection.

Find the head/first element in Set

Here, a set has been created and applied head() operation on Set to find the first/head element in Set.

object SetTest {

  def main(args: Array[String]): Unit = {
    var set: Set[Int] = Set(12, 2, 3, 4, 5, 6, 7, 8, 9)

    print(set.head)
  }
}

Output

5

Find the tail element in Set

Here, a set has been created and applied tail() operation on Set to find the rest of the collection without its first element.

object SetTest {

  def main(args: Array[String]): Unit = {
    var set: Set[Int] = Set(12, 2, 3, 4, 5, 6, 7, 8, 9)

    print(set.tail)
  }
}

Output

Set(6, 9, 2, 12, 7, 3, 8, 4)

References: Scala Set official documentation

I hope you like this tutorial. Thanks for reading and please give us a thumb up and comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.