Merging two sequences in scala in an orderly fashion

scala join two lists by key
scala zip
scala add element to seq

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
      else
      {
        arr = arr :+ b;break; 
      }
    }
  }
  println(arr)

the output that I require needs to be :

Seq(1,2,3,4,5,6,7,8,9)    

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)

How to merge Scala sequential collections (List, Vector, ArrayBuffer , 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,​  Use the ++= method to merge a sequence (any TraversableOnce) into a mutable collection like an ArrayBuffer: scala> val a = collection.mutable.ArrayBuffer (1,2,3) a: scala.collection.mutable.ArrayBuffer [Int] = ArrayBuffer (1, 2, 3) scala> a ++= Seq (4,5,6) res0: a.type = ArrayBuffer (1, 2, 3, 4, 5, 6)

The following also works for non-interleaved sequences:

def mergeSorted[E: Ordering](x: Seq[E], y: Seq[E]): Seq[E] = {
  val ordering = implicitly[Ordering[E]]
  @tailrec
  def rec(x: Seq[E], y: Seq[E], acc: Seq[E]): Seq[E] = {
    (x, y) match {
      case (Nil, Nil) => acc
      case (_, Nil)   => acc ++ x
      case (Nil, _)   => acc ++ y
      case (xh :: xt, yh :: yt) =>
        if (ordering.lteq(xh, yh))
          rec(xt, y, acc :+ xh)
        else
          rec(x, yt, acc :+ yh)
    }
  }
  rec(x, y, Seq())
}

Please note that for performance reasons you'd probably use Builders (vs. :+, +:, reverse).

Befriending the Commedia dell'Arte of Flaminio Scala: The Comic , Use the ++= method to merge a sequence into a mutable sequence. Use the ++ method to merge two mutable or immutable sequences. Use collection methods like union , diff , and intersect. In this tutorial, we will learn how to use Scala's Immutable Sequence and perform common operations such as initialization, adding elements, adding Sequences and creating empty Sequence. And, don't forget to review the Data Structures tutorial before delving into Scala's Immutable and Mutable collections.

I was happy to find @CaringDev's solution and to adapt it to use a Builder:

def mergeSortedBuilder[E: Ordering](x: Seq[E], y: Seq[E])(implicit ordering: Ordering[E]): Seq[E] = {
  @tailrec
  def rec(x: Seq[E], y: Seq[E], acc: Builder[E, Seq[E]]): Builder[E, Seq[E]] = {
  (x, y) match {
    case (Nil, Nil) => acc
    case (_, Nil)   => acc ++= x
    case (Nil, _)   => acc ++= y
    case (xh :: xt, yh :: yt) =>
      if (ordering.lteq(xh, yh))
        rec(xt, y, acc += xh)
      else
        rec(x, yt, acc += yh)
  }
}
rec(x, y, Seq.newBuilder).result
}

Iterators, Each sequence ends with entrances from opposite sides of the stage. it for orations, “not merely in orderly fashion but with a discriminating eye for the exact to each part, and for the joining of parts.69 Quintilian observed that even a slight  For merging a known number of sequences, the first two operators are effectively the same thing and which style you use is a matter of taste: either provide them as a params array or chain the operators together. The third and fourth overloads allow to you merge sequences that can be evaluated lazily at run time.

To interleave two sequences while maintaining their individual ordering, you can use:

scala> seq1.zip(seq2).flatMap(pair => Seq(pair._1,pair._2))
res1: Seq[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)

Note, however, that for sequences of unequal length this loses the extra elements of the longer sequence. That can be sorted out with a bit more effort (find the longer of the two lists, and add longer.drop(shorter.length)).

Python sorted does not work, The two basic operations on an iterator it are next and hasNext . of most of the methods that you find in the Traversable , Iterable and Seq classes. It takes a TraversableOnce parameter, so you can append elements coming from either an it.min, The minimum of the ordered element values returned by iterator it . 10 Use '==' instead of equals for string comparison in Scala Jul 21 '14 9 Merging two sequences in scala in an orderly fashion Oct 18 '13 View all questions and answers →

If you want to interleave an arbitrary number of sequences in order, you can use something like

implicit class Interleave[T](input: Seq[Seq[T]]) {
  def interleave: Seq[T] = {
    input.foldLeft(Seq[Seq[T]]()) { (acc, cur) =>
      if (acc.isEmpty) cur.map { m => Seq(m) }
      else (acc zip cur).map { case (sequence, m) =>
        sequence :+ m
      }
    }.flatten.toVector
  }
}

It may be possible to improve the performance on this, particularly as the toVector is there primarily to transform the stream into something eager.

Usage looks something like

Seq(Seq(1,2), Seq(2,3), Seq(3,4)).interleave should be(Seq(1,2,3,2,3,4))

Scala implementation of Haskell's groupBy - scala - html, 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  Now, if you want to sort a Scala sequence like a List, Vector, ArrayBuffer, Seq, and others, this article shows how to sort those with the sorted and sortWith methods (and the Ordered and Ordering traits). The sorted method can sort collections with type Double, Float, Int, and any other type that has an implicit scala.math.Ordering:

https://stackoverflow.com/questions/19081036/restructuredtext-and-glossary-​terms-translation. Merging two sequences in scala in an orderly fashion - Stack  And this is where the power of merge comes in to efficiently combine multiple data tables together in a nice and orderly fashion into a single dataframe for further analysis. “Merging” two datasets is the process of bringing two datasets together into one, and aligning the rows from each based on common attributes or columns.

Merging two sequences in scala in an orderly fashion 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  The cell death maintains cell numbers, this and mitosis enable structures to enlarge during growth and development but preventing abnormal growth. A receptor on the plasma membrane receives a death signal, which activates caspases that tear apart the cell in an orderly fashion.

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  Dear Annie: My husband and I have been having an argument about this for the past five years, and I am really hoping you can settle it once and for all.Whenever we hit heavy traffic on the interstate because two lanes are merging into one (because of construction, usually), he immediately puts on his signal and tries to merge, meekly puttering along until someone allows him in.

Comments
  • I think it's worth emphasizing in your question that the two input sequences are already sorted, and if not, this would presumably be an error. Is that correct?
  • What if I had dates (elements of type LocalDate to be precise) instead of elements of type Int in the above example? method sorted does not work on dates. what do you suggest?
  • Is there a way to sortBy two types? Like toDate, toPriority? so that it will be first ordered toDate and then toPriority?
  • sortBy(x => (x.toDate, x.toPriority))
  • I am sorry. I had forgotten to add the element '9' at the end.