Reputation: 635
I am trying to convert data that looks like this:
val inputData =
Seq(("STUDY1", "Follow-up", 1),
("STUDY1", "Off Study", 2),
("STUDY1", "Screening", 3),
("STUDY1", "Treatment", 4),
("STUDY2", "Follow-up", 5),
("STUDY2", "Off Study", 6),
("STUDY2", "Screening", 7),
("STUDY2", "Treatment", 8));
into data that looks like this:
val desiredData =
Seq(Seq(1,2,3,4),
Seq(5,6,7,8));
The closest that I've gotten is with this:
val result: Map[String, Seq[Int]] =
data.groupBy(i => i._1)
.mapValues(j => j.map(k => k._3))
.mapValues(_.toArray)
result.values.toSeq
This yields:
res0: Seq[Seq[Int]] = Stream(WrappedArray(1, 2, 3, 4), ?)
That last question mark is throwing me for a loop.
EDIT
Future internet travelers who land here: my code actually did work ... my confusion stemmed from understanding what the ?
was all about. Answers from folks down below helped me see that mapValues
did lazy evaluation, and that the ?
simply implies that.
Upvotes: 2
Views: 1121
Reputation: 14842
mapValues
on Map
is lazy (unlike any other method on a default Map
). So that might be the issue there. Have you tried:
data.groupBy(_._1).map(_._2.map(_._3).toArray)
Note that the toArray
is completely optional here.
Upvotes: 6
Reputation: 802
val result: List[Seq[Int]] =
data.groupBy(_._1).mapValues(_.map(_._3)).values.toList
Upvotes: 3