Extract second tuple element in list of tuples

18,731

Solution 1

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.

Solution 2

Would that work for you?

val a = List(('a',1), ('b', 4), ('c', 3))
a.map(_._2)

Solution 3

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)))
Share:
18,731
More Than Five
Author by

More Than Five

Updated on June 05, 2022

Comments

  • More Than Five
    More Than Five about 2 years

    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?