The Forall() Function in Scala

Suraj P Mar 07, 2022
  1. Iterating Over a Collection With forall() Function in Scala
  2. Use forall() Function With an Empty Collection in Scala
  3. Use forall() With HashMap in Scala
  4. Use forall() With getOrElse() Function in Scala
  5. Difference Between foreach and forall in Scala
  6. Conclusion
The Forall() Function in Scala

This article will show Scala’s forall() function and see various examples to understand its use case.

Scala’s forall() function is used to apply predicate logic over a collection of elements. It is used to check if the predicate logic we applied satisfies all the collection elements.

Syntax:

trait Collection[T] {
  def forall(p: (T) => Boolean): Boolean
}

The forall() function checks if all the elements of the collection satisfy the predicate p and return true or false accordingly as it has a Boolean return type. Let’s look at some instances of applying predicate logic to a collection of elements.

Iterating Over a Collection With forall() Function in Scala

The below example show a snippet where forall is used with Lists.

Example Code:

object workspace  {

  def main(args:Array[String])
  {
    val studentMarks = List(55, 60, 20, 90, 80)

    //applyaing forall method on list
    val result = studentMarks.forall(y => y>=50)

    if(result)
      {
        println("Student passed the examination")
      }
    else
      println("Student has failed the examination")
      }
  }

Output:

Student has failed the examination

The logic is that the element inside the list studentMarks should be greater than or equal to 50. Since 20 is less than 50, the else statement is returned stored in the result variable.

After that, we use the if condition to check the result and print the output accordingly.

Use forall() Function With an Empty Collection in Scala

The forall method always returns true when dealing with an empty collection because none of the elements of the list violate the predicate logic. If there’s no element in the list, the predicate logic is never false.

Example code:

object workspace  {

  def main(args:Array[String])
  {
    val studentMarks = List[Int]()

    //applyaing forall method on list
    val result = studentMarks.forall(y=>y>1)

    if(result)
      {
        println("forall returns true")
      }
    else
      println("forall returns false")
  }
}

Output:

forall returns true

Use forall() With HashMap in Scala

forall is very useful here. Whenever we want to apply some condition on all the keys of HashMap or check if all key-value pairs satisfy a certain condition, we can use the forall() function.

Example code:

import scala.collection.mutable

object workspace {
  def main(args: Array[String]): Unit = {
    val mp = mutable.HashMap[Int, Int](1 -> 100, 2 -> 200, 3->300)

    val allValuesHunderedTimeTheKey = mp.forall { case (key, value) => key * 100 == value }
    println(allValuesHunderedTimeTheKey)
  }
}

Output:

true

We used forall to check that every value is 100 times the value of the key. Since all elements satisfy the predicate, true is returned.

Use forall() With getOrElse() Function in Scala

Example code:

object workspace {
  def main(args: Array[String]): Unit = {
    val names : Option[Seq[String]] = Option(Seq("Iron man", "Tony", "Stark"))
    println(names.map(_.forall(Seq("Bruce").contains)).getOrElse(false))
  }
}

Output:

false

map has created the sequence inside Option to a Boolean value, and then getOrElse the final result, providing a default Boolean value.

Difference Between foreach and forall in Scala

foreach is often confused with forall by beginners. Let’s look at the difference between them.

  1. The foreach function allows us to iterate over a collection of elements.
  2. The forall function takes a Boolean predicate, checks it against all the elements, and returns true if the elements satisfy the condition.

Example code:

object workspace {
  def main(args: Array[String]): Unit = {
    val studentMarks = List(55, 60, 20, 90, 80)

    //applyaing forall method on list
    val result = studentMarks.forall(y => y>=50)

    println(result)

    studentMarks.foreach(x => println(2*x))
  }
}

Output:

false
110
120
40
180
160

Using forall(), we are checking that every element is greater than or equal to 50, it returns false as element 20 fails the condition and using foreach(), we are iterating over all the elements and just printing the double of that element.

Conclusion

We learned about Scala’s forall() function and its use in various conditions to apply predicate logic to a collection of elements in this article.

Author: Suraj P
Suraj P avatar Suraj P avatar

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

LinkedIn GitHub