You can use the groupBy
method. Here's an example in a REPL session:
scala> case class MyObject(id: Long, iq: Long)
defined class MyObject
scala> val xs = List(MyObject(1, 2), MyObject(1, 3), MyObject(2, 4))
xs: List[MyObject] = List(MyObject(1,2), MyObject(1,3), MyObject(2,4))
scala> val groupedById = xs.groupBy(_.id)
groupedById: scala.collection.immutable.Map[Long,List[MyObject]] = Map(2 -> List(MyObject(2,4)), 1 -> List(MyObject(1,2), MyObject(1,3)))
scala> val idToIqs = groupedById.mapValues(_.map(_.iq))
idToIqs: scala.collection.immutable.Map[Long,List[Long]] = Map(2 -> List(4), 1 -> List(2, 3))
I used an intermediate value, groupedById
, so you can see what happens along the way.