Reputation: 6152
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?
Upvotes: 0
Views: 104
Reputation: 176
@jwvh's anwser is good.
just give another pattern-matching version.
o1.zip(o2).map{case (item1, item2) => s"$item1 & $item2"}.mkString(", ")
Upvotes: 2
Reputation: 51271
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.
Upvotes: 1