Scala list splitAt() operation with examples

 125 total views,  2 views today

Welcome to the Scala series. In this tutorial, you will learn about the Scala List splitAt() operation with examples.

Scala splitAt() operation allows us to split the collection into two different collections based on the given index.

splitAt() takes an index which then splits the collection into two different collections based on the index.

splitAt() returns a tuple that has two lists and accepts an integer.

splitAt() Syntax

def splitAt(n: Int): (List[A], List[A])

Splits this list into a prefix/suffix pair at a given position.

Scala List splitAt() examples

In this splitAt() example, we have created a list of person objects and applied splitAt() operation to split the persons based on the index.

It returns a tuple that will have two lists separated based on the index.

object SplitAtTest {

  def main(args: Array[String]): Unit = {

    case class Person(var name: String, age: Int)

    //create a List
    var list = List(Person("Raj", 27), Person("John", 27), Person("Sri", 26), Person("Radha", 26), Person("Wick", 28))

    //Apply span
    var result: (List[Person], List[Person]) = list.splitAt(2)

    result._1.foreach(println)
    println("-----------------------")
    result._2.foreach(println)

  }
}

Output

Person(Raj,27)
Person(John,27)
-----------------------
Person(Sri,26)
Person(Radha,26)
Person(Wick,28)

Let us see another example of splitAt() where we split a list of integers based on an index

object SplitAtTest {

  def main(args: Array[String]): Unit = {

     //create List
    var list1 = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

    //Apply span
    var ouput: (List[Int], List[Int]) = list1.splitAt(4);

    ouput._1.foreach(println)
    println("-----------------------")
    ouput._2.foreach(println)

  }
}

Output

1
2
3
4
-----------------------
5
6
7
8
9

ReferencesScala splitAt() operation

Would you like to learn more about Scala features, please check out Scala – a complete guide series. In this tutorial guide, you will find useful Scala functions that can be applied to the collection.

I hope you like this tutorial and you were able to understand the Scala list splitAt() operation with examples.

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.