Skip to content

Instantly share code, notes, and snippets.

@dcbriccetti
Created December 28, 2014 21:58
Show Gist options
  • Save dcbriccetti/f56a6d9351b267e8305a to your computer and use it in GitHub Desktop.
Save dcbriccetti/f56a6d9351b267e8305a to your computer and use it in GitHub Desktop.
Can you simplify this, please?
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))
@deanwampler
Copy link

You could use a mutable MultiMap:

import collection.mutable.{HashMap, MultiMap, Set}
val mm = new HashMap[Int, Set[Int]] with MultiMap[Int, Int]
as.foldLeft(mm)((mm, a) => mm.addBinding(a.b, a.a))

See the MultiMap scaladocs for more details.

@teigen
Copy link

teigen commented Dec 29, 2014

// 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