10.22. Merging Sequential Collections
Problem
You want to join two sequences into one sequence, either keeping all of the original elements, finding the elements that are common to both collections, or finding the difference between the two sequences.
Solution
There are a variety of solutions to this problem, depending on your needs:
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
, andintersect
.
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)
Use the ++
method to merge two
mutable or immutable collections while assigning the result to a new
variable:
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)
You can also use methods like union
and intersect
to combine sequences to create a
resulting sequence:
scala>val a = Array(1,2,3,4,5)
a: Array[Int] = Array(1, 2, 3, 4, 5) scala>val b = Array(4,5,6,7,8)
b: Array[Int] = Array(4, 5, 6, 7, 8) // elements that are in both collections scala>val c = a.intersect(b)
c: Array[Int] = Array(4, 5) // all elements from both collections scala>val c = a.union(b)
c: Array[Int] ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.