scala - 在 scala 中漂亮地打印嵌套 Map

标签 scala

假设我在 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/

相关文章:

Scala运行时的安全性

Scala错误: value <FUNCTION_NAME> is not a member of object <OBJECT_NAME>

scala - 从消费类隐式消费

scala - Scala 的列表是否在连接运算符下形成了幺半群?

scala - Reader monad 有什么好处?

scala - 部分应用和返回函数之间有区别吗?

java - 使用 Scala 中的 vararg 参数覆盖 Java 方法时出现 AbstractMethodError

scala - 重载具有多个参数列表的方法是否违法?

scala - 为什么 Scala 有时需要在匿名函数中命名的参数?

scala - 在 spark 中设置 textinputformat.record.delimiter