Scala - List[MyObject] -> Map[Long, List[Long]]

瘦欲@ 提交于 2019-12-25 01:46:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!