Scala Iterate Over List of Objects (Different Ways)

1. Introduction

Iterating over a list of objects is a common task in Scala, especially when dealing with collections of custom data types. Scala provides several ways to iterate over such lists, each with its own advantages. This post will demonstrate different methods to iterate over a list of objects in Scala.

2. Program Steps

1. Create a Scala case class to define a custom data type.

2. Define a list of objects of the case class.

3. Show different ways to iterate over the list, including using foreach, map, and for comprehension.

4. Execute the code and observe the output to understand each method's functionality.

3. Code Program

case class Person(name: String, age: Int)

object ListOfObjectsIterationDemo extends App {
  val people = List(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))

  // Using foreach
  println("Using foreach:")
  people.foreach(person => println(s"${person.name} is ${person.age} years old"))

  // Using map to transform objects
  println("\nUsing map to increase age by 1:")
  val olderPeople = people.map(person => Person(person.name, person.age + 1))
  olderPeople.foreach(person => println(s"${person.name} is ${person.age} years old"))

  // Using for comprehension
  println("\nUsing for comprehension:")
  for (person <- people) {
    println(s"${person.name} is ${person.age} years old")
  }
}

Output:

Using foreach:
Alice is 30 years old
Bob is 25 years old
Charlie is 35 years old
Using map to increase age by 1:
Alice is 31 years old
Bob is 26 years old
Charlie is 36 years old
Using for comprehension:
Alice is 30 years old
Bob is 25 years old
Charlie is 35 years old

Explanation:

1. foreach is used to iterate over the people list and execute a block of code for each object, printing the name and age.

2. map transforms each Person object in the list into a new object, in this case, incrementing the age by 1. The resulting list is iterated with foreach to print the updated information.

3. For comprehension provides a syntactic sugar for iterating over the list, similar to the foreach method, but it can be more readable and convenient for complex iterations or when involving conditions.


Comments