Here, we will create two objects of Vector collection. Then we will merge two vectors using the "++" operator. After that, we will print the result on the console screen.
The Vector is an immutable data structure. We can access vector elements randomly. It extends an abstract class AbstractSeq and IndexedSeq trait. We use the Vector collection to store a large number of elements.
The source code to merge two vectors using the "++" operator is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to merge two vectors
import scala.collection.immutable._
object Sample {
// Main method
def main(args: Array[String]) {
var vector1 = Vector(10, 20, 30);
var vector2 = Vector(40, 50);
var vectorNew = vector1 ++ vector2;
println(vectorNew);
}
}
Output:
Vector(10, 20, 30, 40, 50)
Explanation:
Here, we used an object-oriented approach to create the program. And, we imported Collection classes using the below statement,
import scala.collection.immutable._
And, we also created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.
In the main() function, we created two vectors vector1, vector2 using Vector collection. Then we merged both vectors using the "++" operator and assigned the result into vectorNew. After that, we printed the elements of vectorNew on the console screen.
Program/Source Code:
The source code to merge two vectors using the "++" operator is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Output:
Explanation:
Here, we used an object-oriented approach to create the program. And, we imported Collection classes using the below statement,
And, we also created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.
In the main() function, we created two vectors vector1, vector2 using Vector collection. Then we merged both vectors using the "++" operator and assigned the result into vectorNew. After that, we printed the elements of vectorNew on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer