Created
December 28, 2014 21:58
-
-
Save dcbriccetti/f56a6d9351b267e8305a to your computer and use it in GitHub Desktop.
Can you simplify this, please?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scala> case class A(a: Int, b: Int) | |
defined class A | |
scala> val as = Seq(A(1, 100), A(2, 100), A(3, 101)) | |
as: Seq[A] = List(A(1,100), A(2,100), A(3,101)) | |
scala> as.groupBy(_.b) | |
res3: scala.collection.immutable.Map[Int,Seq[A]] = Map(101 -> List(A(3,101)), 100 -> List(A(1,100), A(2,100))) | |
scala> res3.map{case (b, as) => b -> as.map(_.a)} | |
res5: scala.collection.immutable.Map[Int,Seq[Int]] = Map(101 -> List(3), 100 -> List(1, 2)) |
// using mapValues simplifies it a tiny bit
as.groupBy(_.b).mapValues(_.map(_.a))
// scalaz allows you to sum any foldable which has a monoid. Map has a monoid when its value-type has a monoid, which in this case is a List (which has a monoid)
import scalaz._
import std.map._ // monoid for Map
import std.list._ // monoid for List
import syntax.foldable._ // suml
as.toList.map{ case A(a,b) => Map(b -> List(a))}.suml
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could use a mutable MultiMap:
See the MultiMap scaladocs for more details.