Scala – Combine two lists in an alternating fashion

How do I merge 2 lists in such a way that the resulting list contains the elements of 2 lists in alternating fashion in Scala.


val list1 = List("Mary", "a", "lamb")

val list2 = List("had", "little")


List("Mary", "had", "a", "little", "lamb")


What you’re looking for is usually called “intersperse” or “intercalate” and there are a few ways to do it:

def intersperse[A](a : List[A], b : List[A]): List[A] = a match {
  case first :: rest => first :: intersperse(b, rest)
  case _             => b

You can also use scalaz

import scalaz._
import Scalaz._

val lst1 = ...
val lst2 = ...

lst1 intercalate lst2

Edit: You can also do the following:

lst1.zipAll(lst2,"","") flatMap { case (a, b) => Seq(a, b) }

Come to think of it, I believe the last solution is my favorite since it’s most concise while still being clear. If you’re already using Scalaz, I’d use the second solution. The first is also very readable however.

And just to make this answer more complete, adding @Travis Brown’s solution that is generic:, Nil, Nil).flatMap(Function.tupled(_ ::: _))

Source : Link , Question Author : yAsH , Answer Author : yan

Leave a Comment