Scala list takeWhile() operation with examples

 191 total views,  4 views today

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

Scala takeWhile() operation allows us to take the first prefix elements that satisfy the given predicate from the collection. takeWhile() operation will return new collection with prefix elements but it should satisfy the given boolean/predicate expression.

Scala takeWhile() operation is applicable to all types of Scala collections.

takeWhile() Syntax

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

Takes longest prefix of elements that satisfy a predicate.

p - The predicate used to test elements.

returns - the longest prefix of this list whose elements all satisfy the predicate p.

Scala List takeWhile() examples

In this takeWhile() example, we have created a list and applied takeWhile() method to get the first prefix elements that are less than 4.

The first element should at least satisfy the given boolean expression else it will return empty. Boolean expression is executed from left to right of the collection.

object TakeWhileTest {

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

    //Create a list
    var list = List(1, 2, 3, 4, 5, 6, 7, 8);

    //Apply takeWhile() and print collection
    list.takeWhile(ele => ele < 4).foreach(println)

  }
}

Output

1
2
3

Let us see another example on takeWhile() where the output is an empty list because the first element of the collection doesn’t satisfy the given condition while the next elements satisfy.

object TakeWhileTest {

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

    //Create a list
    var list = List(6, 2, 3, 4, 5, 6, 7, 8);

    //Apply takeWhile() and print collection
    list.takeWhile(ele => ele < 4).foreach(println)

  }
}

Output 

<empty>

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

1 thought on “Scala list takeWhile() operation with examples

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.