Converting a list to a map in Scala

I want to create a simple program that calculates someone's age after x years. so first you assign someone's current age to a variable, and then I want to use map to display the future ages. What I have so far is:

val age = 18
val myList = (1 to 2000).toList

Basically, I want the numbers from the list and make it a map key. And for the value, it's a sum of variable and key. so the map would look like this: 1 -> 19, 2 -> 20, 3 -> 21......

How can I accomplish this?

1 answer

  • answered 2020-02-12 23:04 Mario Galic

    Consider mapping to tuples

    val age = 18
    val ageBy: Map[Int, Int] = (1 to 2000).map(i => i -> (age + i)).toMap
    ageBy(24)   // res1: Int = 42