假设我在 Scala 中有一个下一个 Map,如下所示:
type MapType = Map[String, Map[String, Map[String, (String, String)]]]
val m: MapType = Map("Alphabet" -> Map( "Big Boss" -> Map("Clandestine Mssion" -> ("Dracula Returns", "Enemy at the Gates"))))
println(m)
这将输出如下所示的 map :
Map(Alphabet -> Map(Big Boss -> Map(Clandestine Mssion -> (Dracula Returns,Enemy at the Gates))))
我怎样才能像下面这样打印它?:
Map(
Alphabet -> Map(Big Boss -> Map(
Clandestine Mssion -> (Dracula Returns,Enemy at the Gates)
)
)
)
或者以类似于漂亮嵌套 JSON 的方式。
最佳答案
这应该可以解决问题
object App {
def main(args : Array[String]) {
type MapType = Map[String, Map[String, Map[String, (String, String)]]]
val m: MapType = Map("Alphabet" -> Map( "Big Boss" -> Map("Clandestine Mssion" -> ("Dracula Returns", "Enemy at the Gates"))))
println(m.prettyPrint)
}
implicit class PrettyPrintMap[K, V](val map: Map[K, V]) {
def prettyPrint: PrettyPrintMap[K, V] = this
override def toString: String = {
val valuesString = toStringLines.mkString("\n")
"Map (\n" + valuesString + "\n)"
}
def toStringLines = {
map
.flatMap{ case (k, v) => keyValueToString(k, v)}
.map(indentLine(_))
}
def keyValueToString(key: K, value: V): Iterable[String] = {
value match {
case v: Map[_, _] => Iterable(key + " -> Map (") ++ v.prettyPrint.toStringLines ++ Iterable(")")
case x => Iterable(key + " -> " + x.toString)
}
}
def indentLine(line: String): String = {
"\t" + line
}
}
}
输出为
Map (
Alphabet -> Map (
Big Boss -> Map (
Clandestine Mssion -> (Dracula Returns,Enemy at the Gates)
)
)
)
关于scala - 在 scala 中漂亮地打印嵌套 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32004050/