我是 Scala 和 Spark 的新手,我正在努力执行以下操作, 我正在尝试将 Seq 转换为 Map,同时在转换序列时通过添加“_suffix”来修改值,如下所示:
val columns = Seq($"col2",$"col3")
val map = columns.map(t => t.toString() -> t.toString()+"_suffix").toMap
但是,我收到以下错误:
scala> val map = columns.map(t => t.toString() -> t.toString()+"_suffix").toMap
<console>:25: error: Cannot prove that String <:< (T, U).
val map = columns.map(t => t.toString() -> t.toString()+"_suffix").toMap
此外,.map
结果返回以下内容:
scala> val map = columns.map(t => t.toString() -> t.toString()+"_suffix")
map: Seq[String] = List((col2,col2)_suffix, (col3,col3)_suffix)
这就是我想要制作的:
map: Seq[(String, String)] = List((col2,col2_suffix), (col3,col3_suffix)
所以我最终可以将它转换成 map :
map: scala.collection.immutable.Map[String,String] = Map(col2 -> col2_suffix, col3 -> col3_suffix)
我在尝试实现这一目标时遇到了困难,有什么建议吗?
最佳答案
你所做的是正确的,只需添加一些括号即可:
columns.map(t => t.toString() -> (t.toString() + "_suffix")).toMap
从结果中可以看出,“_suffix”
被添加到元组的字符串中,即
(col2,col2)_suffix
您想要做的是将字符串仅添加到第二个元素,因此括号是必需的。
关于scala - 如何将 Seq[Column] 转换为 Map[String,String] 并更改值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699530/