Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading