转换元组数组的最佳功能方法是什么?
Array[(String, String)]
到地图
Map[String, String]
尝试了以下方法:
def arrayToMap(array:Array[(String, String)]):Map[String, String] = {
array.foldLeft(Map.empty[String, String]) ((x,y) => (x->y))
}
但显示此编译错误:
type mismatch; found : (scala.collection.immutable.Map[String,String], (String, String)) required: scala.collection.immutable.Map[String,String]
改为使用toMap()
,如下所示:
def arrayToMap(array:Array[(String, String)]):Map[String, String] = {
array.toMap()
}
给出以下内容:
not enough arguments for method toMap: (implicit ev: (String, String) <:< (T, U))scala.collection.immutable.Map[T,U]. Unspecified value parameter ev.
谢谢
答案 0 :(得分:2)
使用地图:
@ val a: Array[(String, String)] = Array(("a", "b"), ("c", "d"))
a: Array[(String, String)] = Array(("a", "b"), ("c", "d"))
@ a.toMap
res1: Map[String, String] = Map("a" -> "b", "c" -> "d")
答案 1 :(得分:0)
删除参数,然后替换
toMap()
使用
toMap
解决了问题