0

I'm very new to scala and am trying to achieve the following:

I have a list of objects like so:

groups = [{id=1, iq=2}, {id=1,iq=3}, {id=2, iq=4}]

How can build a map[Long,List[Long]] from groups?

eg.

[{1, [2,3]}, {2,[4]}]

Any suggestions would be very much appreciated :)

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
DMcg
  • 129
  • 3
  • 11
  • 1
    Possible duplicate of [How can a reduce a key value pair to key and list of values?](https://stackoverflow.com/questions/26780348/how-can-a-reduce-a-key-value-pair-to-key-and-list-of-values) (Specifically [Sergey Lagutin's answer](https://stackoverflow.com/a/26780440/2707792)) – Andrey Tyukin Jul 06 '18 at 14:14

1 Answers1

3

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.

lambdista
  • 1,850
  • 9
  • 16