Reputation: 10429
I have a Map where each value is a list of Tuples such as:
List(('a',1), ('b', 4), ('c', 3)....)
what is the most scala-thonic way to change each value is still a LIst but is only the second element of each Tuple
List(1,4,3)
I have tried
myMap.mapValues(x => x._2)
And I get
error: value _2 is not a member of List[(Char, Integer)]
any tips?
Upvotes: 12
Views: 21122
Reputation: 763
Another way is using unzip
which turns a list of tuples into a tuple of lists. It is especially useful if you actually want both values from the tuples.
val list = List(('a',1), ('b', 4), ('c', 3))
val (letters, numbers) = list.unzip
// letters: List[Char] = List(a, b, c)
// numbers: List[Int] = List(1, 4, 3)
Upvotes: 0
Reputation: 166
Would that work for you?
val a = List(('a',1), ('b', 4), ('c', 3))
a.map(_._2)
Upvotes: 8
Reputation: 236
Note that mapValues() returns a view on myMap. If myMap is mutable and is modified, the corresponding changes will appear in the map returned by mapValues. If you really don't want your original map after the transformation, you may want to use map() instead of mapValues():
myMap.map(pair => (pair._1, pair._2.map(_._2)))
Upvotes: 2
Reputation: 35463
Try this:
myMap.mapValues(_.map(_._2))
The value passed to mapValues
is a List[(Char,Integer)]
, so you have to further map that to the second element of the tuple.
Upvotes: 10