Scala forall method with examples

 520 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala forall method with examples.

Scala forall method is used for testing each element of a collection. It is a predicate operation which returns a boolean value based on some validation performed on each item of the collection.

Normal way of validating each item in a collection. The below example is imperative style programming

object StaticReference {

  def main(args: Array[String]) {
    val list = List(1, 2, 3, 4, 5);
    for (item <- list){
      if(item < 10){
        true;
      }else{
        false;
      }
    }
  }
}

Scala list forall example

Scala forall applies a function to each item of the collection. This is functional style programming

object StaticReference {

  def main(args: Array[String]) {
    val list = List(1, 2, 3, 4, 5);

    val ouput = list.forall(item => {
      if (item < 10) {
        true
      } else false
    })
  }
}

Scala Seq forall example

object StaticReference {

  def main(args: Array[String]) {
    val seq = Seq(1, 2, 3, 4, 5);

    val ouput = seq.forall(item => {
      if (item < 10) {
        true
      } else false
    })
  }
}

Scala map forall example

object StaticReference {

  def main(args: Array[String]) {
    val map = Map("apple" -> 1, "orange" -> 2, "banana" -> 3)
    map.forall({
      case (key, value) => {
        if (key.equalsIgnoreCase("apple")) {
          true
        } else {
          false
        }
      }
    })
  }
}

References Official documentation

Thanks for reading Scala forall method with examples. Please leave us a comment and give us a thumbs up!

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!.