Kevin van Heel
Kevin van Heel

Reputation: 29

Scala: using map to extract secondary tuple values from a list

My problem is the following:

I have a list of a specific type, lets call it A. A is defined by A(name:String, value: Int).

This would make my list look like [("a", 10) ("b", 12) ("c" 14)].

Now I want to use a map function to extract only the secondary values. that is construct a new list of the values [10,12,14]. I've been trying for over an hour but can't seem to get it working.

I've tried it with pattern matching in a map function and by trying to take the second element, i.e:

myList.map(_.value) 

or

myList.map(_.2) 

but can't seem to get it working.

Upvotes: 0

Views: 2354

Answers (2)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

If your list is a Tuple2 as

val list = List(("a", 10), ("b", 12), ("c", 14))
//list: List[(String, Int)] = List((a,10), (b,12), (c,14))

You have to use method _1 to access the first element, _2 to access the second, and so on. So doing the following should solve

list.map(_._2)
//res0: List[Int] = List(10, 12, 14)

But if its defined as a case class as

case class A(name:String, value: Int)
//defined class A

val list = List(A("a", 10), A("b", 12), A("c", 14))
//list: List[A] = List(A(a,10), A(b,12), A(c,14))

Then your way is correct

list.map(_.value)
//res0: List[Int] = List(10, 12, 14)

Upvotes: 3

prayagupadhyay
prayagupadhyay

Reputation: 31222

if your data-structure is case class then, what you are doing is correct,

scala> case class Data(name:String, value: Int) 
// defined case class Data
scala> Seq(Data("a", 1), Data("b", 2), Data("c", 3)).map(_.value) 
val res6: Seq[Int] = List(1, 2, 3)

But if its not a data class but a tuple, then you would have to get the second element using tuple._2 or with pattern match as below

scala> Seq(("a", 1), ("b", 2), ("c", 3)).collect {case (name, value) => value } 
res7: Seq[Int] = List(1, 2, 3)

Also Read syntax for scala tuple

Upvotes: 3

Related Questions