问题
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 :)
回答1:
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.
来源:https://stackoverflow.com/questions/51212195/scala-listmyobject-maplong-listlong