Scala - Merging two Arrays or ArrayBuffers

Scala Array FAQ: How do I merge two Arrays or ArrayBuffers?

Solution: Use the ++ method to join two arrays into one new array:

scala> val a = Array(1,2,3)
a: Array[Int] = Array(1, 2, 3)

scala> val b = Array(4,5,6)
b: Array[Int] = Array(4, 5, 6)

scala> val c = a ++ b
c: Array[Int] = Array(1, 2, 3, 4, 5, 6)

ArrayBuffer

Use the same approach to merge two ArrayBuffers into a new ArrayBuffer:

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val a = ArrayBuffer(1,2,3)
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

scala> val b = ArrayBuffer(4,5,6)
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(4, 5, 6)

scala> val c = a ++ b
c: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6)

scala> c
res0: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6)

As with other collection types, the ++ method is used to join two Arrays or ArrayBuffers.

Because it's mutable, the ArrayBuffer can also use methods like ++= and += to "merge" other data elements into it:

scala> val a = ArrayBuffer(1,2,3)
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

scala> a ++= ArrayBuffer(4,5,6)
res0: a.type = ArrayBuffer(1, 2, 3, 4, 5, 6)

scala> a += (7,8,9)
res1: a.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9)

If you need to merge/join an Array or ArrayBuffer with other Scala collections, I hope this quick tip has been helpful.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.