How to convert a Seq[A] to a Map[Int, A] using a value of A as the key in the map?

前端 未结 4 1325
野趣味
野趣味 2021-01-31 07:59

I have a Seq containing objects of a class that looks like this:

class A (val key: Int, ...)

Now I want to convert this Seq<

4条回答
  •  长发绾君心
    2021-01-31 08:23

    One more 2.8 variation, for good measure, also efficient:

    scala> case class A(key: Int, x: Int)
    defined class A
    
    scala> val l = List(A(1, 2), A(1, 3), A(2, 1))
    l: List[A] = List(A(1,2), A(1,3), A(2,1))
    
    scala> val m: Map[Int, A] = (l, l).zipped.map(_.key -> _)(collection.breakOut)
    m: Map[Int,A] = Map((1,A(1,3)), (2,A(2,1)))
    

    Note that if you have duplicate keys, you'll discard some of them during Map creation! You could use groupBy to create a map where each value is a sequence:

    scala> l.groupBy(_.key)
    res1: scala.collection.Map[Int,List[A]] = Map((1,List(A(1,2), A(1,3))), (2,List(A(2,1))))
    

提交回复
热议问题