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 program of foreach() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(6, 2, 3, 4, 5) // Applying foreach method to print the stack print("Elements in the stack: ") s1.foreach(x => print(x + " ")) } } |
chevron_right
filter_none
Output:
Elements in the stack: 6 2 3 4 5
Example #2:
// Scala program of foreach() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(6, 2, 3, 4, 5) // Print the stack println(s1) // Applying foreach method s1.foreach(x => println(x + " times " + x +" = " + x*x)) } } |
chevron_right
filter_none
Output:
Stack(6, 2, 3, 4, 5) 6 times 6 = 36 2 times 2 = 4 3 times 3 = 9 4 times 4 = 16 5 times 5 = 25
Recommended Posts:
- Scala Map foreach() method with example
- Scala Set foreach() method with example
- Scala Queue foreach() method with example
- Scala SortedSet foreach() method with example
- Scala SortedMap foreach() method with example
- Scala TreeSet foreach() method with example
- Scala Mutable SortedMap foreach() method with example
- Program to apply foreach() method on Java Set in Scala
- Program to apply foreach() method on Java List in Scala
- Program to apply foreach() method on Java Set of integers in Scala
- Program to apply foreach() method on java list of strings in Scala
- Program to apply foreach() method on java list of characters in Scala
- Program to apply foreach() method on Java Set of characters in Scala
- Scala Mutable SortedSet foreach() method
- Scala immutable TreeSet foreach() method
- Scala Stack ++ method with example
- Scala Stack ++:() method with example
- Scala Stack +:() method with example
- Scala Stack :+() method with example
- Scala Stack /:() method with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

