Scala List dropWhile() operation with examples

 255 total views,  2 views today

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

dropWhile() operation is a useful operation of the Scala List which allows us to drop prefix elements from the list or collection based on a given predicate function. When you call this operation on a Scala list, it returns a new collection by dropping the first prefix elements matching the given boolean condition.

dropWhile() Syntax

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

Drops longest prefix of elements that satisfy a predicate.

Scala List dropWhile() example

In this example , we have created a list of elements ranging from 1 to 9.We apply dropWhile() operation that allows to us drop prefix elements that match the given condition.i.,e it will drop prefix elements that are less than 5.

object DropWhile {

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

    //create a List
    var list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

    //Drop prefix elements that are less than 5
    list.dropWhile(ele => ele < 5).foreach(println _)
  }

}

Output

5
6
7
8
9

For example, if you have a list of elements as (5,1,2,3,4,5,6,7) and applying dropWhile() to drop elements that are less than 5. Your output will be (5,1,2,3,4,5,6,7) which is unchanged. This is because prefix elements should match the given predicate. i.e., at least the first element should match the predicate.

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

    //create a List
    var list: List[Int] = List(5,1,2,3,4,5,6,7)

    //Drop prefix elements that are less than 5
    list.dropWhile(ele => ele < 5).foreach(println _)
  }
}

Output

5
1
2
3
4
5
6
7

ReferencesScala dropWhile() operation

I hope you like this tutorial and you were able to understand Scala list dropWhile() 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!.