我正在尝试将Map的内容展平为字符串列表。
所以这个集合:
val d: scala.collection.immutable.Map[String, scala.collection.immutable.Seq[Any]] =
Map("b" -> List(Array(1.0, 2.0), 5.333333333333333),
"d" -> List(Array(3.0, 3.0), 8.0))
应转换为List[String]
类型的两个元素:
b,1,2,5.3
d 3,3,8.0
要实现此目的,我尝试使用以下方法分解地图并展平其键:
d.map(m =>
m match {
case(k , v) => {
(k , v.flatten)
}
})
但我收到错误:
Multiple markers at this line - No implicit view available from Any => scala.collection.GenTraversableOnce[B]. -
not enough arguments for method flatten: (implicit asTraversable: Any =>
scala.collection.GenTraversableOnce[B])scala.collection.immutable.Seq[B]. Unspecified value parameter
asTraversable.
如何将集合scala.collection.immutable.Map[String, scala.collection.immutable.Seq[Any]]
转换为List[String]
?
更新:
This works :
val map: Map[String, scala.collection.immutable.Seq[Any]] =
Map(
"bsds" -> List(Array(1.0, 2.0), 5.333333333333333),
"dsdfsd" -> List(Array(3.0, 3.0), 8.0)
) //> map : Map[String,scala.collection.immutable.Seq[Any]] = Map(bsds -> List(Ar
//| ray(1.0, 2.0), 5.333333333333333), dsdfsd -> List(Array(3.0, 3.0), 8.0))
val flatten = map.map {
case (k : String , v) =>
val expanded = v map {
case arr: Array[_] => Seq(arr: _*)
case el : Double => Seq(el)
}
(k , (expanded.flatten))
} //> flatten : scala.collection.immutable.Map[String,scala.collection.immutable.
//| Seq[Any]] = Map(bsds -> List(1.0, 2.0, 5.333333333333333), dsdfsd -> List(3.
//| 0, 3.0, 8.0))
val ll = flatten.map(m => List(m._1) ++ m._2) //> ll : scala.collection.immutable.Iterable[List[Any]] = List(List(bsds, 1.0,
//| 2.0, 5.333333333333333), List(dsdfsd, 3.0, 3.0, 8.0))
ll.map(m => m.mkString("|")) //> res5: scala.collection.immutable.Iterable[String] = List(bsds|1.0|2.0|5.3333
//| 33333333333, dsdfsd|3.0|3.0|8.0)
答案 0 :(得分:1)
val map: Map[String, scala.collection.immutable.Seq[Any]] =
Map(
"b" -> List(Array(1.0, 2.0), 5.333333333333333),
"d" -> List(Array(3.0, 3.0), 8.0)
)
val flatten = map.map {
case (k, v) =>
val expanded = v map {
case arr: Array[_] => Seq(arr: _*)
case el => Seq(el)
}
(k ++ expanded.flatten).mkString(",")
}
flatten.foreach(println)
答案 1 :(得分:0)
不像你想要的那样平坦:
scala> import runtime.{ ScalaRunTime => RT }
import runtime.{ScalaRunTime=>RT}
scala> val m = Map("bcde" -> List(Array(1.0, 2.0), 5.333333333333333), "fghij" -> List(Array(3.0, 3.0), 8.0))
m: scala.collection.immutable.Map[String,List[Any]] = Map(bcde -> List(Array(1.0, 2.0), 5.333333333333333), fghij -> List(Array(3.0, 3.0), 8.0))
scala> m map { case (k,v) => s"${RT stringOf k}, ${v map (RT stringOf _) mkString ", "}" }
res7: scala.collection.immutable.Iterable[String] = List(bcde, Array(1.0, 2.0), 5.333333333333333, fghij, Array(3.0, 3.0), 8.0)
但值得做广告。
答案 2 :(得分:0)
使用for comprehension,像这样,
for ( (k, List(Array(a,b,_*),v)) <- d) yield Seq(k,a,b,v).mkString(",")