0

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.

user unknown
  • 35,537
  • 11
  • 75
  • 121
  • 3
    If indeed these are tuples (and not instances of a case class like `A`) - use `myList.map(_._2) ` – Tzach Zohar Feb 28 '18 at 18:37
  • @TzachZohar is correct if your data structure is `Tuple`, but you are confusing engineers here showing a data class `A(name:String, value: Int)` . – prayagupa Feb 28 '18 at 18:55
  • 2
    You say the question is solved but neither answer has been accepted or even up-voted. That's not the way to say thanks on SO. – jwvh Feb 28 '18 at 19:22
  • Yes, agreeing with @jwvh. If non of both answers solved your problem, give a self answer (or do you need more reputation to do so?). But if one answer solved your problem, accept it as answer, and vote every answer up, which you find good. It costs you less than editing the question, and the system will not recognize your edit as 'solved'. But it will recognize 'accepted answer' (colorized answer counter in the question list). Btw.: We avoid here greetings, 'Thanks in advance', 'Please help me out' and such. And the 'solved' message pollutes the auto generated excerpt - another point against. – user unknown Feb 28 '18 at 20:06

2 Answers2

3

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)
Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
3

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

prayagupa
  • 30,204
  • 14
  • 155
  • 192