Scala - Multiple ways to iterate over a list

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:

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

    scala
    val numbers = List(1, 2, 3, 4, 5) numbers.foreach { num => println(s"Element: $num") }
  2. Using a for Loop:

    You can use a for loop to iterate over the elements of a list and perform actions on them.

    scala
    val fruits = List("apple", "banana", "cherry") for (fruit <- fruits) { println(s"Fruit: $fruit") }
  3. 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.

    scala
    val numbers = List(1, 2, 3, 4, 5) val squaredNumbers = numbers.map(num => num * num) println(squaredNumbers) // Output: List(1, 4, 9, 16, 25)
  4. Using for...yield:

    You can combine a for loop with yield to create a new list by applying a transformation to each element.

    scala
    val numbers = List(1, 2, 3, 4, 5) val squaredNumbers = for (num <- numbers) yield num * num println(squaredNumbers) // Output: List(1, 4, 9, 16, 25)
  5. 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.

    scala
    val 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
  6. Using while Loop:

    Although functional programming constructs are preferred in Scala, you can use a while loop for iterative processing.

    scala
    val numbers = List(1, 2, 3, 4, 5) var index = 0 while (index < numbers.length) { println(s"Element: ${numbers(index)}") index += 1 }
  7. Using Recursion:

    You can also iterate over a list using recursion. Here is an example of a recursive function to process a list:

    scala
    def 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.

Search
Related Articles

Leave a Comment: