scala 通过遍历地图构建字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5985266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:00:36  来源:igfitidea点击:

scala build up string from iterating over map

scala

提问by user747980

if i have a map and want to build up a string from iterating over it, is there a way to have the final string be a result of an expression instead of defining a variable and modifying that inside a loop?

如果我有一张地图并想通过对其进行迭代来构建一个字符串,有没有办法让最终字符串成为表达式的结果,而不是定义一个变量并在循环内修改它?

instead of this

而不是这个

val myMap = Map("1" -> "2", "3"->"4") 
var s = ""
myMap foreach s += ...

i'd rather it be

我宁愿它是

var s = myMap something ...

采纳答案by Ben James

You can do this with a fold:

你可以用折叠来做到这一点:

scala> myMap.foldLeft("") { (s: String, pair: (String, String)) =>
     |   s + pair._1 + pair._2
     | }
res0: java.lang.String = 1234

回答by Daniel C. Sobral

I'd just mapand mkString. For example:

我只是mapmkString。例如:

val s = (
    Map("1" -> "2", "3"->"4") 
    map { case (key, value) => "Key: %s\nValue: %s" format (key, value) } 
    mkString ("", "\n", "\n")
)

回答by Kevin Wright

As for Daniel's answer, but with a couple of optimisations and my own formatting preferences:

至于丹尼尔的回答,但有一些优化和我自己的格式偏好:

val myMap = Map("1" -> "2", "3"->"4")
val s = myMap.view map {
  case (key, value) => "Key: " + key + "\nValue: " + value
} mkString ("", "\n", "\n")

The optimisations:

优化:

  1. By first creating a viewof the map, I avoid creating an intermediate collection
  2. On profiling, direct String concatenation is faster than String.format
  1. 通过首先创建view地图的一个,我避免创建一个中间集合
  2. 在分析时,直接字符串连接比 String.format

回答by Diego Sevilla

I'm fairly new to Scala, but you can try reduceLeft. It goes accumulating a partial value (the string being joined with every element). For example, if you want the keys (or the values) joined in a string, just do:

我对 Scala 还很陌生,但你可以试试reduceLeft. 它会累积一个部分值(与每个元素连接的字符串)。例如,如果您希望将键(或值)连接到一个字符串中,只需执行以下操作:

val s = myMap.keys.reduceLeft( (e, s) =>  e + s)

This results in "13"

这导致“ 13

回答by Antonin Brettsnajdr

This works also fine if you don't bother about your own formatting:

如果您不担心自己的格式,这也很好用:

scala> Map("1" -> "2", "3"->"4").mkString(", ")
res6: String = 1 -> 2, 3 -> 4