繁体   English   中英

如何在Scala中打印地图

[英]How to print a Map in Scala

好吧,这个问题似乎真的很愚蠢,但我的观点是,如果你看一下Scala 2.7.6 API,他们就不推荐使用mappingToString方法了。 因此,应该有更优雅的替代方案来打印自定义格式的Map。 因为几乎任何目的,在Map中使用mkString的等价方法非常方便。

你们怎么看待它? 除println外,打印地图的编码片段是什么?

mappingToString特定于Map

使用Scala2.8中的新集合框架,可以通过任何IterableLike迭代Map ,它可以扩展TraversableLike

然后应该使用方法mkstring (已经在2.7中用于Iterable )。

有关2.7 mkstring()示例,请参阅Jesse的博客文章“Strings”

/*
   Making use of raw strings to create a multi line string
   I add a | at the beginning of each line so that we can line up the quote nicely 
   in source code then later strip it from the string using stripMargin
*/
scala> val quote = """|I  don-t consider myself a pessimist.                                                                                                 
     |                |I think of a pessimist as someone who is waiting for it to rain.
     |                |And I feel soaked to the skin.
     | 
     |                |Leonard Cohen"""
quote: java.lang.String = 
|I don-t consider myself a pessimist. 
                      |I think of a pessimist as someone who is waiting for it to rain.
                      |And I feel soaked to the skin.

                      |Leonard Cohen

// capilize the first character of each line
scala> val capitalized = quote.lines.
     |                         map( _.trim.capitalize).mkString("\n")
capitalized: String = 
|I don-t consider myself a pessimist.
|I think of a pessimist as someone who is waiting for it to rain.
|And I feel soaked to the skin.

|Leonard Cohen

// remove the margin of each line
scala> quote.stripMargin        
res1: String = 
I don-t consider myself a pessimist. 
I think of a pessimist as someone who is waiting for it to rain.
And I feel soaked to the skin.

Leonard Cohen

// this is silly.  I reverse the order of each word but keep the words in order
scala> quote.stripMargin.         
     |       lines.               
     |       map( _.split(" ").   
     |              map(_.reverse).
     |              mkString (" ")).
     |      mkString("\n")
res16: String = 
I t-nod redisnoc flesym a .tsimissep
I kniht fo a tsimissep sa enoemos ohw si gnitiaw rof ti ot .niar
dnA I leef dekaos ot eht .niks

dranoeL nehoC

mappingToString方法用于更改每对键/值转换为String的方式,然后由toString方法使用。

我觉得这很糟糕。 一方面,它为其他不可变数据结构添加了可变性。 如果您有特定的打印要求,那么最好将它们放在另一个类中。

您还可以将Iterator.map()mkString()结合使用,例如从map[String,String]创建查询字符串:

val queryString = updatedMap.map(pair => pair._1+"="+pair._2).mkString("?","&","")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM