Arrays are important data structures in programming and there may arise times when we have two different arrays and we need to merge them into one for processing. This is the case when you need array concatenation which is the process to merge to arrays by appending the elements of the second array after the elements of the first array.
Arrays in Scala are generally immutable, so we need to create a new array that will store the concatenated array in Scala. Or another method could be creating mutable arrays that will save memory.
For merging two arrays Scala provides you multiple methods and we will discuss them one by one in this example.
1) Using the concat() method
In Scala, there is a method named concat() that is used to concatenate two arrays.
Syntax:
This method returns an array which is a concatenated array.
Program to concatenate two arrays using concat() method
Output
2) Using the ++ method
To merge two arrays into one ++ method can also be used.
Syntax:
This will return the merge array.
Program to concatenate two arrays using ++ method
Output
Merging two mutable arrays (arrayBuffers)
We can assign the concatenated array to any of the existing arrays when they are mutable. Both methods, concat() and ++ apply to ArrayBuffer also. A method assignment method can also be applied to the ArrayBuffer which is +=.
Program to concatenate two ArrayBuffer into one
Output
need an explanation for this answer? contact us directly to get an explanation for this answer