Home > Back-end >  How do I add the output of a for-loop to a list in Scala?
How do I add the output of a for-loop to a list in Scala?

Time:03-31

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:

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.

CodePudding user response:

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.

CodePudding user response:

You can use map function as @Tim explained or just use yield like in:

val list = for ((_,b) <- y) yield b
  • Related