简体   繁体   English

如何将Map [String,Seq [String]]转换为Map [String,String]

[英]How to convert Map[String,Seq[String]] to Map[String,String]

我有一个Map [String,Seq [String]]并希望基本上将它转换为Map [String,String],因为我知道序列只有一个值。

Someone else already mentioned mapValues , but if I were you I would do it like this: 其他人已经提到了mapValues ,但如果我是你,我会这样做:

scala> val m = Map(1 -> Seq(1), 2 -> Seq(2))
m: scala.collection.immutable.Map[Int,Seq[Int]] = Map(1 -> List(1), 2 -> List(2))

scala> m.map { case (k,Seq(v)) => (k,v) }
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2)

Two reasons: 两个原因:

  1. The mapValues method produces a view of the result Map, meaning that the function will be recomputed every time you access an element. mapValues方法生成结果Map的视图 ,这意味着每次访问元素都会重新计算该函数。 Unless you plan on accessing each element exactly once, or you only plan on accessing a very small percentage of them, you don't want that recomputation to take place. 除非您计划一次访问每个元素,或者您只计划访问其中的一小部分,否则您不希望重新计算。

  2. Using a case with (k,Seq(v)) ensures that an exception will be thrown if the function ever sees a Seq that doesn't contain exactly one element. 使用的情况下与(k,Seq(v))确保如果函数曾经看到一个不包含一个元素一个序列的异常将被抛出。 Using _(0) or _.head will throw an exception if there are zero elements, but will not complain if you had more than one, which will likely result in mysterious bugs later on when things go missing without errors. 如果有零个元素,使用_(0)_.head将抛出一个异常,但如果你有多个元素则不会抱怨,这可能会在以后丢失没有错误的情况下导致神秘的错误。

You can use mapValues() . 您可以使用mapValues()

scala> Map("a" -> Seq("aaa"), "b" -> Seq("bbb"))
res0: scala.collection.immutable.Map[java.lang.String,Seq[java.lang.String]] = M
ap(a -> List(aaa), b -> List(bbb))

scala> res0.mapValues(_(0))
res1: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(a
-> aaa, b -> bbb)

我想通过以下方式得到了它:

mymap.flatMap(x => Map(x._1 -> x._2.head))

Yet another suggestion: 还有一个建议:

m mapValues { _.mkString }

This one's agnostic to whether the Seq has multiple elements -- it'll just concatenate all the strings together. 这个与Seq是否有多个元素无关 - 它只是将所有字符串连接在一起。 If you're concerned about the recomputation of each value, you can make it happen up-front: 如果您担心每个值的重新计算,您可以预先做到:

(m mapValues { _.mkString }).view.force

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM