如何在Scala中打印地图

时间:2009-10-23 06:29:56

标签: scala formatting map

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

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

3 个答案:

答案 0 :(得分:3)

mappingToString特定于Map

使用Scala2.8中的新集合框架,任何Map都可以迭代IterableLikemkstring()扩展/* 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

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

有关2.7 {{1}}示例的信息,请参阅此Iterable

{{1}}

答案 1 :(得分:3)

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

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

答案 2 :(得分:3)

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

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