Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-01 01:56:25 Viewed : 262
In Scala, you can iterate over a Set using various methods, including for loops, foreach, map, and more. Here are multiple ways to iterate over a Set in Scala with output:
1. Using a For-Each Loop:
scalaval mySet = Set(1, 2, 3, 4, 5) for (item <- mySet) { println(item) }
2. Using the foreach
Method:
scalaval mySet = Set(1, 2, 3, 4, 5) mySet.foreach(item => println(item))
3. Using map
and foreach
(functional approach):
scalaval mySet = Set(1, 2, 3, 4, 5) mySet.map(item => println(item))
4. Using a While Loop and an Iterator:
scalaval mySet = Set(1, 2, 3, 4, 5) val iterator = mySet.iterator while (iterator.hasNext) { val item = iterator.next() println(item) }
5. Using a for
comprehension (functional approach):
scalaval mySet = Set(1, 2, 3, 4, 5) for { item <- mySet } println(item)
6. Using a Tail-Recursive Function:
scalaimport scala.annotation.tailrec val mySet = Set(1, 2, 3, 4, 5) @tailrec def printSet(set: Set[Int]): Unit = { if (set.nonEmpty) { val (item, remainingSet) = (set.head, set.tail) println(item) printSet(remainingSet) } } printSet(mySet)
These are some common ways to iterate over a Set in Scala, each with its own syntax and style. You can choose the one that best fits your coding preferences and the specific requirements of your application.