Scala Convert List to Map

1. Introduction

Converting a list to a map is a common task in Scala, especially when you want to improve the lookup performance or organize the data more effectively. This process involves transforming each element of a list into a key-value pair. In this post, we will explore how to convert a list into a map in Scala.

2. Program Steps

1. Define a Scala list.

2. Transform the list into a map using various methods, such as map and toMap.

3. Demonstrate the conversion process.

4. Print the resulting map to verify the transformation.

3. Code Program

object ListToMapDemo extends App {
  case class Person(name: String, age: Int)
  val peopleList = List(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))

  // Converting list to map with 'name' as key and 'age' as value
  val peopleMap = peopleList.map(person => person.name -> person.age).toMap
  println("Map with name as key and age as value:")
  println(peopleMap)

  // Converting list to map with 'name' as key and 'Person' object as value
  val peopleMap2 = peopleList.map(person => person.name -> person).toMap
  println("\nMap with name as key and Person object as value:")
  println(peopleMap2)
}

Output:

Map with name as key and age as value:
Map(Alice -> 30, Bob -> 25, Charlie -> 35)
Map with name as key and Person object as value:
Map(Alice -> Person(Alice,30), Bob -> Person(Bob,25), Charlie -> Person(Charlie,35))

Explanation:

1. We define a case class Person and a list of Person objects.

2. The first conversion uses the map method to transform each Person object in the list into a tuple of (name, age), and then the toMap method is used to convert the list of tuples into a map.

3. In the second conversion, the map method creates a tuple of (name, Person object), which is then transformed into a map using toMap. This way, the map's value is the entire Person object.

4. Both maps are printed, showing the different ways of converting a list into a map in Scala.


Comments