Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-09-27 23:27:41 Viewed : 284
Multiple ways to iterate over a list:
In Scala, there are multiple ways to iterate over a list (or any collection) to process its elements. Here are some common ways to iterate over a list in Scala, along with examples:
Using foreach
:
The foreach
method allows you to apply a function to each element of the list. It is a concise way to perform an operation on each element without the need for explicit indexing.
scalaval numbers = List(1, 2, 3, 4, 5) numbers.foreach { num => println(s"Element: $num") }
Using a for
Loop:
You can use a for
loop to iterate over the elements of a list and perform actions on them.
scalaval fruits = List("apple", "banana", "cherry") for (fruit <- fruits) { println(s"Fruit: $fruit") }
Using map
:
The map
method applies a given function to each element of the list and returns a new list containing the results of the function calls.
scalaval numbers = List(1, 2, 3, 4, 5) val squaredNumbers = numbers.map(num => num * num) println(squaredNumbers) // Output: List(1, 4, 9, 16, 25)
Using for...yield
:
You can combine a for
loop with yield
to create a new list by applying a transformation to each element.
scalaval numbers = List(1, 2, 3, 4, 5) val squaredNumbers = for (num <- numbers) yield num * num println(squaredNumbers) // Output: List(1, 4, 9, 16, 25)
Using foldLeft
:
foldLeft
is a higher-order function that allows you to accumulate a result while iterating over the list. It takes an initial value and a function that combines the current result with the next element.
scalaval numbers = List(1, 2, 3, 4, 5) val sum = numbers.foldLeft(0)((acc, num) => acc + num) println(s"Sum of numbers: $sum") // Output: Sum of numbers: 15
Using while
Loop:
Although functional programming constructs are preferred in Scala, you can use a while
loop for iterative processing.
scalaval numbers = List(1, 2, 3, 4, 5) var index = 0 while (index < numbers.length) { println(s"Element: ${numbers(index)}") index += 1 }
Using Recursion:
You can also iterate over a list using recursion. Here is an example of a recursive function to process a list:
scaladef processList(list: List[Int]): Unit = list match { case Nil => // Base case: empty list case head :: tail => println(s"Element: $head") processList(tail) } val numbers = List(1, 2, 3, 4, 5) processList(numbers)
Choose the iteration method that best suits your use case and coding style. Functional approaches like map
, foreach
, and foldLeft
are often preferred in Scala because they promote immutability and composability.