Core_Dumped Core_Dumped - 6 months ago 32
Scala Question

Merging two sequences in scala in an orderly fashion

I am trying to merge two sequences such that they remain sorted. The following is the code that I have written:

val seq1 = Seq(1,3,5,7,9)
val seq2 = Seq(2,4,6,8)
var arr = Seq[Int]()
for(b <- seq2)
for(a <- seq1)
if(a < b)
arr = arr :+ a
arr = arr :+ b;break;

the output that I require needs to be :


But it seems break does not work in Scala. I am relatively new to the language. What would be the best way to carry out this operation?


The simplest way would probably be this:

(seq1 ++ seq2).sorted

If seq1 and seq2 contain some other type, you'll have to provide an Ordering for that type; or, alternatively, use the sortBy method, mapping each element to an element of another type for which an Ordering can implicitly be found:

(seq1 ++ seq2).sortBy(_.toDate)