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 do I add the output of a for-loop to a list in Scala?

I’m looking to iterate over a list of tuples and extract the second value from each tuple. I’d then like to add these values to a new list.

Each tuple in my list consists of a string and an int:

y = List((this, 1), (is, 2), (a, 3), (test, 4)

I can successfully iterate over each tuple and extract the int using:

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

for (x <- y) {

val intValue = x._2

println(intValue)

}

This gives me

1

2

3

4

I’m then looking to add those values to a list. Any help would be appreciated.

>Solution :

There is no need to use for here, a simple map will do:

y.map(_._2)

The map function creates a new List from the old one by calling a function on each element of the List.

The function _._2 is a shorthand for x => x._2. This just returns the second value in the tuple, which is the Int you want to extract.

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