Scala list span() operation with examples

88 total views, 1 views today

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

Scala span() operation allows us to split the collection into two different collections based on the given predicate operation.span() takes a predicate/boolean expression, prefix elements satisfying the condition will be added to one list and the element which doesn’t satisfy will be added to a separate list. span() returns a tuple that has two lists.

span() Syntax

def span(p: (A) => Boolean): (List[A], List[A])

Splits this list into a prefix/suffix pair according to a predicate.

Scala List span() examples

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

object Span {

  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.span(ele => ele.age == 27);

    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)

In another span() example, we have created a list of integers and have applied span() to split if the element is greater than 5.

object Span {

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

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

    //Apply span
    var ouput: (List[Int], List[Int]) = list1.span(ele => ele > 5);

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

  }
}

Output

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

ReferencesScala span() 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 span() 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.