Home > Blockchain >  How to map the values inside a list with an integer in Scala?
How to map the values inside a list with an integer in Scala?

Time:04-18

I am so fresh in Scala and Functional Programming. And I am stuck with an operation with collections in Scala. I have a variable like that:

    val res4: List[(List[Double], Option[Int])] = 
List(
(List(4.0, 2.0, 3.0, 4.0, 3.0, 2.5, 4.0),Some(1998)), 
(List(3.0, 4.0, 3.0, 3.0, 3.5, 2.0, 3.0, 3.0, 4.0).Some(2000),
.......
)

I want to have a map or something like that by using each score in the list:

(4.0, Some(1998)),
(2.0, Some(1998)),
(3.0, Some(1998)),
(4.0, Some(1998)),
(3.0, Some(1998)),
(2.5, Some(1998)),
(4.0, Some(1998)),
(3.0, Some(2000)),
....

How can i do that?

Furhermore, If you know the tip about how to transform Some(1998) into 1998, I will be so appreciated.

CodePudding user response:

You can use flatMap:

List(
    (List(4.0, 2.0, 3.0, 4.0, 3.0, 2.5, 4.0), Some(1998)),
    (List(3.0, 4.0, 3.0, 3.0, 3.5, 2.0, 3.0, 3.0, 4.0), Some(2000))
  )
    .flatMap(row => row._1.map(number => (number, row._2)))
    .foreach(it => println(it))
  • Related