我想以正确的格式显示数据,我有以下代码
val maplist=List(Map("id" -> "1", "Name" -> "divya"),
Map("id" -> "2", "Name" -> "gaya")
)
val header=maplist.flatMap(_.keys).distinct
val data=maplist.map(_.values)
println(header.mkString(" "))
data.foreach(x => println(x.mkString(" ")))
显示为
id Name
1 divya
2 gaya
但我想表现出来,我可能要使用df.show()函数
+----+-----+
|Id |Name |
+----+-----+
|1 |Divya|
|2 |gaya |
+----+-----+
答案 0 :(得分:0)
如果您需要分隔符,则应使用mkString
方法和更多参数,您可以查看API
mkString(start:String,sep:String,end:String):String
在字符串中显示此可遍历或迭代器的所有元素 使用开始,结束和分隔符字符串。
val separatorLine = "+----+-----+"
val separator = "|"
val maplist=List(Map("id" -> "1", "Name" -> "divya"),
Map("id" -> "2", "Name" -> "gaya")
)
val header=maplist.flatMap(_.keys).distinct
val data=maplist.map(_.values)
println(separatorLine)
println(header.mkString("|", " |", "|"))
println(separatorLine)
data.foreach(x => println(x.mkString("|", " |", "|")))
println(separatorLine)
结果:
+----+-----+
|id |Name|
+----+-----+
|1 |divya|
|2 |gaya|
+----+-----+
更新:如果你想在每个字符串(例如5)中使用相同的长度,你可以做一个辅助方法,你需要在需要时附加空格:
@tailrec
private def appendElem(original : String, desiredLength: Int, c: Char): String = {
if (original.length < desiredLength)
appendElem(original + c, desiredLength, c)
else {
original
}
}
val separator = "|"
val maplist=List(Map("id" -> "1", "Name" -> "divya"),
Map("id" -> "2", "Name" -> "gaya")
)
val separatorLine = List.fill(maplist.size)( "+").map(appendElem(_, 6,'-')).mkString+ "+"
val header=maplist.flatMap(_.keys.map(key => appendElem(key, 5, ' '))).distinct
val data=maplist.map(_.values)
println(separatorLine)
println(header.mkString("|", "|", "|"))
println(separatorLine)
data.map(x => x.map(y => appendElem(y, 5, ' '))).foreach(x => println(x.mkString("|", "|", "|")))
println(separatorLine)
对于第二个版本,结果如下
+-----+-----+
|id |Name |
+-----+-----+
|1 |divya|
|2 |gaya |
+-----+-----+