简体   繁体   中英

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:

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?

@jwvh's anwser is good.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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