Scala Set foreach() method with example Last Updated : 18 Oct, 2019 Comments Improve Suggest changes Like Article Like Report The foreach() method is utilized to apply the given function to all the elements of the set. Method Definition: def foreach(f: (A) => Unit): Unit Return Type: It returns all the elements of the set after applying the given function to each of them. Example #1: Scala // Scala program of foreach() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(3, 7, 12, 9, 21) // Applying foreach method s1.foreach(x => println(x)) } } Output: 21 9 12 7 3 Example #2: Scala // Scala program of foreach() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) // Applying foreach method s1.foreach(x => println(x + " times " + x + " = " + x*x)) } } Output: 5 times 5 = 25 1 times 1 = 1 2 times 2 = 4 3 times 3 = 9 4 times 4 = 16 Comment More infoAdvertise with us Next Article Scala Set foreach() method with example R rupesh_rao Follow Improve Article Tags : Scala Scala Scala-Method scala-collection Scala-Set +1 More Similar Reads Scala Stack foreach() method with example In Scala Stack class, the foreach() method is utilized to apply a given function to all the elements of the stack. Method Definition: def foreach[U](f: (A) => U): Unit Return Type: It returns all the elements of the stack after applying the given function to each of them. Example #1: Scala // Sca 2 min read Scala TreeSet foreach() method with example In Scala TreeSet class, the foreach() method is utilized to apply a given function to all the elements of the TreeSet. Method Definition: def foreach[U](f: (A) => U): Unit Return Type: It returns all the elements of the TreeSet after applying the given function to each of them. Example #1: Scala 2 min read Scala Set forall() method with example The forall() method is utilized to check if the given predicate satisfies all the elements of the set or not. Method Definition: def forall(p: (A) => Boolean): Boolean Return Type: It returns true if the stated predicate holds true for all the elements of the set else it returns false. Example #1 1 min read Scala SortedSet foreach() method with example The foreach() method is utilized to apply the given function to all the elements of the SortedSet. Method Definition: def foreach(f: (A) => Unit): Unit Return Type: It returns all the elements of the SortedSet after applying the given function to each of them. Example #1: Scala // Scala program o 1 min read Scala SortedMap foreach() method with example The foreach() method is utilized to apply the given function to all the elements of the SortedMap. Method Definition: def foreach(f: ((A, B)) => Unit): Unit Return Type: It returns all the elements of the SortedMap after applying the given function to each of them. Example #1: Scala // Scala prog 1 min read Like