この質問は本当にばかげているようですが、Scala 2.7.6 APIを見れば、mappingToStringメソッドは廃止されました。したがって、カスタム形式のマップを印刷するためのよりエレガントな代替手段が必要です。ほぼすべての目的のために、MapにmkStringの等価メソッドを持たせるのは本当に便利です。Scalaで地図を印刷するには
あなたはどう思いますか? println以外のMapを印刷するためのコーディングスニペットは何ですか?
この質問は本当にばかげているようですが、Scala 2.7.6 APIを見れば、mappingToStringメソッドは廃止されました。したがって、カスタム形式のマップを印刷するためのよりエレガントな代替手段が必要です。ほぼすべての目的のために、MapにmkStringの等価メソッドを持たせるのは本当に便利です。Scalaで地図を印刷するには
あなたはどう思いますか? println以外のMapを印刷するためのコーディングスニペットは何ですか?
mappingToString
方法は、キー/値の各ペアは、その後toString
方法によって使用された文字列に変換された方法を変更するために使用しました。
私はそれがひどいフィットだと思う。これは、他の方法では変更できないデータ構造に変更可能性を追加します。特定の印刷要件がある場合は、おそらく別のクラスに入れる方がよいでしょう。
mappingToString
は、Map
に特異的であった。
Scala2.8の新しいコレクションフレームワークでは、Map
はIterableLike
(これはTraversableLikeです)で繰り返すことができます。
(Iterable
の場合はmkstringのメソッド2.7)が使用されます。
2.7 mkstring()
例については、このblog post "Strings" by Jesse参照:
/*
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
またmap[String,String]
からクエリ文字列を作成するには、たとえば、mkString()
でIterator.map()
を組み合わせることができます
val queryString = updatedMap.map(pair => pair._1+"="+pair._2).mkString("?","&","")
良い点を不変クラスであることに! – Ekkmanz