[英]iterate on scala list and treating last iteration differently
I have a list of objects that I am calling toString
on, and would like to treat the last object differently as follows: 我有一个要调用toString
的对象列表,并且希望对最后一个对象的处理方式如下:
o1 = Array(...)
o2 = Array(...) // same length as o1
sb = new StringBuilder()
for (i <- 0 to o1.size() - 1)
sb.append(o1.get(i).toString() + " & " o2.get(i).toString())
// if not last iteration then append ", "
is there a simple way to write this in scala rather than checking value of i
etc? 有没有一种简单的方法可以在scala中编写此代码,而不是检查i
等的值?
@jwvh's anwser is good. @jwvh的答案很好。
just give another pattern-matching version. 只需给出另一个模式匹配版本。
o1.zip(o2).map({case (item1, item2) => s"$item1 & $item2"}).mkString(", ")
Give this a try. 试试看。
o1.zip(o2).map(t => s"${t._1} & ${t._2}").mkString(", ")
Zip the arrays together, turn each pair into the desired string, let mkString()
insert the commas. 将数组压缩在一起,将每对变成所需的字符串,然后让mkString()
插入逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.