Supposing I have a list of tuples:
val temp = List((string1, int1), (string2, int2), (string1, int3))
and I wanted it to groupBy to become a Map of the following format, how could I do it?
Map(string1 -> List(int1, int3), string2 -> List(int2))
If I use groupBy directly, it will result in something like this:
temp.groupBy(x => x._1)
// output
Map(string1 -> List((string1,int1),(string1,int3)), string2 -> List((string2,int2)))
I understand that mapValue might be useful in this case, but I couldn't wrap my head around this.
CodePudding user response:
With the first groupBy you have in the string1
case this list: List((string1,1), (string1,3))
You can map it to only keep the second value with .map { case (k,v) => (k,v.map(_._2))}
Working example
val temp = List(("string1", 1), ("string2", 2), ("string1", 3))
println(temp.groupBy(_._1).map { case (k,v) => (k,v.map(_._2))})