First, I'd consider grouping by the first 2 elements of each line in one swoop, rather than a nested operation. And I'd use a regex to parse each line, which I find a lot easier to look at than "split":
scala> val input =
| """tom,c,lakers
| tom,pf,lakers
| tom,c,rockets
| tom,pf,knicks
| dick,sg,cavs
| dick,sf,bulls
| dick,sg,heat
| harry,pg,mavs
| harry,pg,wizards
| harry,pg,clippers"""
input: String =
tom,c,lakers
tom,pf,lakers
tom,c,rockets
tom,pf,knicks
dick,sg,cavs
dick,sf,bulls
dick,sg,heat
harry,pg,mavs
harry,pg,wizards
harry,pg,clippers
scala> val linePattern = "([^,]+),([^,]+),([^,]+)".r
linePattern: scala.util.matching.Regex = ([^,]+),([^,]+),([^,]+)
scala> val tuples = scala.io.Source.fromString(input).getLines.toList.collect {
| case linePattern(name, pos, team) => (name, pos, team)
| }
tuples: List[(String, String, String)] = List((tom,c,lakers), (tom,pf,lakers), (tom,c,rockets), (tom,pf,knicks), (dick,sg,cavs), (dick,sf,bulls), (dick,sg,heat), (harry,pg,mavs), (harry,pg,wizards), (harry,pg,clippers))
scala> for( ((name, pos), teams) <- tuples.groupBy(t => (t._1, t._2)).mapValues(_.map(_._3).mkString(","))) {
| println(s"${name} played ${pos} for ${teams}")
| }
harry played pg for mavs,wizards,clippers
tom played c for lakers,rockets
tom played pf for lakers,knicks
dick played sg for cavs,heat
dick played sf for bulls
Brian Maso
--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
case class Entry(
player: String,
position: String,
team: String
)
scala.io.Source.fromFile("playas.csv").getLines.toSeq
.map(_.split(","))
.map { case Array(player, position, team) => Entry(player, position, team) }
.groupBy(entry => (entry.player, entry.position)) // see how this is already much nicer?
.foreach {
case ((player, position), entries) =>
val teams = entries.map(_.team).distinct
println(s"$player played $position for (${teams.mkString("|")})"
}