Search code examples
scala

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?


Solution

  • @jwvh's anwser is good.

    just give another pattern-matching version.

    o1.zip(o2).map{case (item1, item2) => s"$item1 & $item2"}.mkString(", ")